Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement is_enum_class type trait? [duplicate]

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

+T{};

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.

like image 948
Inkane Avatar asked Nov 14 '14 18:11

Inkane


2 Answers

You check whether the enumeration is convertible to int.

template <class T>
using is_scoped_enum = std::integral_constant<bool, !std::is_convertible<T,int>{}
                                                  && std::is_enum<T>{}>;

These static assertions will succeed:

enum e {};
enum class e2 {};

static_assert( is_scoped_enum<e2>::value, "" );
static_assert( !is_scoped_enum<e>::value, "" );
static_assert( !is_scoped_enum<char>::value, "" );

Demo.

like image 114
Columbo Avatar answered Oct 25 '22 15:10

Columbo


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

DEMO

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

DEMO 2

Tests:

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, "!");
}
like image 36
Piotr Skotnicki Avatar answered Oct 25 '22 13:10

Piotr Skotnicki