Inkane Inkane - 4 months ago 43
C++ Question

How to implement is_enum_class type trait?

How can one implement type trait whose value member is true if and only if the passed in type T is a class enum? While I know that for instance


will work if T is an enum and fail if it is an enum class, I couldn't find a way so far to use this for SFINAE.


Based on your +T{} test:

Option #1:

Expression SFINAE in trailing return type:

#include <type_traits>

template <typename T>
auto test(int) -> decltype((void)+T{}, std::false_type{});

template <typename T>
auto test(...) -> std::true_type;

template <typename T>
using is_enum_class = std::integral_constant<bool, decltype(test<T>(0))::value && std::is_enum<T>::value>;


Option #2:

In void_t-fashion:

template <typename T, typename V = void>
struct test : std::false_type {};

template <typename T>
struct test<T, decltype((void)+T{})> : std::true_type {};

template <typename T>
using is_enum_class = std::integral_constant<bool, !test<T>::value && std::is_enum<T>::value>;



enum class EC { a, b };
enum E { c, d };

int main()
    static_assert(is_enum_class<EC>::value, "!");
    static_assert(!is_enum_class<E>::value, "!");
    static_assert(!is_enum_class<int>::value, "!");