确保模板参数是枚举类 [英] Ensure template parameter is an enum class

查看:85
本文介绍了确保模板参数是枚举类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确保模板参数是枚举类类型?

Is there a way to ensure a template parameter is an enum-class type?

我知道 type_traits 具有 std :: is_enum ,但我不希望它与常规枚举匹配,只是enum_classes。

I know type_traits has std::is_enum, but I don't want it to match regular enums, just enum_classes.

示例想要的效果:

enum class EnumClass {};
enum Enum {};
class Class {};

template <typename T>
void Example()
{
    static_assert(/* T is EnumClass */, "`T` must be an enum class");
}

Example<EnumClass>(); // Ok
Example<Enum>(); // Error
Example<Class>(); // Error

我使用的是C ++ 11,但不幸的是它无法再提高了(尽管我d仍然想知道该解决方案,即使它涉及较新的标准也是如此。)

I am using C++11, and unfortunately cannot go any higher (though I'd be curious to know the solution anyway, even if it involves newer standards).

有可能吗?

推荐答案

您可以通过以下方式实现:

You can achieve it with:

template<typename T>
using is_class_enum = std::integral_constant<
   bool,
   std::is_enum<T>::value && !std::is_convertible<T, int>::value>;

此处

如果您更喜欢使用SFINAE,则可以使用以下方法实现:

If you prefer using SFINAE, the same can be achieved with:

template<typename T, typename _ = void>
struct is_class_enum : std::false_type {
};

template<typename T>
struct is_class_enum <
  T,
  typename std::enable_if<std::is_enum<T>::value &&
                          !std::is_convertible<T, int>::value>::type> :
    public std::true_type {
};

这篇关于确保模板参数是枚举类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆