Ensure template parameter is an enum class [duplicate]
Asked Answered
R

1

21

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

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

Example of the wanted effect:

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

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).

Is it possible?

Reganregard answered 1/10, 2016 at 14:12 Comment(0)
E
22

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

Here a demo.


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 {
};
Ejaculatory answered 1/10, 2016 at 14:18 Comment(5)
Correct me if I'm wrong, but you're simply depending on the fact that enum classes are not implicitly convertible to integrals? Isn't it possible to define an implicit conversion operator?Reganregard
@GiladNaaman how do you define an implicit operator from an enum class?Ejaculatory
Yeah, my bad, you can't actually define operators or functions inside an enum class.Reganregard
Shouldn't std::underlying_type_t<T> be used instead of just an int as a std::is_convertible<> check type?Recitativo
@SergeyNikitin There's no point, and doing underlying_type right is actually tricky (you cannot instantiate it until you know that T is actually an enum type).Cacology

© 2022 - 2024 — McMap. All rights reserved.