22
votes

Is there a type trait, or is it possible to write a type trait is_scoped_enum<T> such that:

  • if T is a scoped enumeration, is_scoped_enum<T>::value is true and
  • if T is any other type, is_scoped_enum<T>::value is false
1
By scoped enum, you meant C++11's enum?Nawaz
@Nawaz: A scoped enum is what an enum class is called in C++11, yes.James McNellis
Just out of curiosity, what practical applications are there for this one?Xeo
@Xeo: I am overloading the bitwise operators for a set of scoped enumeration types.James McNellis

1 Answers

34
votes

I think testing if it is an enum and not implicitly convertible to the underlying type should do the trick.

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> {};