是否可以确定类型是否为范围枚举类型?

Jam*_*lis 16 c++ enums metaprogramming type-traits c++11

是否有类型特征,或者是否可以编写类型特征is_scoped_enum<T>,使得:

  • if T是一个范围枚举,is_scoped_enum<T>::valuetrue
  • 如果T是任何其他类型,is_scoped_enum<T>::value则为false

R. *_*des 29

我认为测试它是否是枚举并且不能隐式转换为基础类型应该可以解决问题.

template <typename T, bool B = std::is_enum<T>::value>
struct is_scoped_enum : std::false_type {};

template <typename T>
struct is_scoped_enum<T, true>
: std::integral_constant<bool,
    !std::is_convertible<T, typename std::underlying_type<T>::type>::value> {};
Run Code Online (Sandbox Code Playgroud)

  • 更好地使用`std :: underlying_type <T>`而不是`int`.C++ 11中的`enum class`可以基于不可转换为`int`的东西. (2认同)
  • @Excelcius这比出错的可能性更糟糕:使用带有非枚举类型的`std::underlying_type`是未定义的行为,不需要诊断,所以编译器不需要报告误用,然后给你的程序UB。我没有研究常见的实现,但假设标准允许 UB 在有效用例中更容易实现。 (2认同)