C++11 metaprogramming - lookup enum value during compilation (values contains gaps)

c++, c++11, enums, metaprogramming

Solution

enum myenum { val1 = 10, val2 = 30, val3 = 45 };
template<myenum e> struct is_valid_myenum { static const bool value = (e==val1 || e==val2 || e==val3); };

template<myenum t>
class myClass
{
    static_assert(is_valid_myenum<t>::value, "t must be a valid enum value");
};

myClass<10> a; // fails, OK
myClass<val1> b; // compiles OK
myClass<myenum(24)> c; // fails, OK

If you really, really want to avoid the duplication (and aren't interested in using some external tool to generate sourcecode) you can resort to macro hackery.

#define LIST \
    ITEM(val1,10)\
    ITEM(val2,30)\
    ITEM(val3,45)

#define ITEM(NAME,VALUE) NAME = VALUE,

enum myenum { LIST };

#undef ITEM

#define ITEM(NAME,VALUE) e==NAME ||

template<myenum e> struct is_valid_myenum { static const bool value = ( LIST false ); };

template<myenum t>
class myClass
{
    static_assert(is_valid_myenum<t>::value, "t must be a valid enum value");
};

myClass<10> a; // fails, OK
myClass<val1> b; // compiles OK
myClass<myenum(24)> c; // fails, OK

Problem

Is there a way, at compile-time, to verify that a given value is within the values of a given enum, thus valid? ``` enum myenum { val1 = 10, val2 = 30, val3 = 45 } template <myenum t> class myClass { ... } myClass<10> a; // fails, OK myClass<val1> b; // compiles OK myClass<myenum(24)> c; //compiles, NOT OK! ``` Using a second template non-type boolean parameter would be useful in there, and the value of that boolean would be given by a meta-function, that given a value would verify that the value is within the values of myenum. I looked through various enum related question, like how to iterate an enum, and it seems it can't be done.

Original source