Using answer from Substitution failure is not an error (SFINAE) for enum I tried to write a code that would get enum value from a class, and if this enum value is not found it would have a fallback value. As I'm beginner with templates, after couple of hours I gave up and found a "solution" using macros :(
Is there a way to do the same thing without macros and without copying the code for every possible enum value?
This is what I came up with:
struct foo
{
enum FooFields
{
enumFoo,
enumHehe
};
};
struct bar
{
enum BarFields
{
enumHehe = 2
};
};
#define GETENUM_DEF(testedEnum) \
template<class T> \
struct get_ ## testedEnum{\
typedef char yes;\
typedef yes (&no)[2];\
\
template<int>\
struct test2;\
\
template<class U>\
static int test(test2<U::testedEnum>*){return U::testedEnum;};\
template<class U>\
static int test(...){return -1;};\
\
static int value(){return test<T>(0);}\
};
GETENUM_DEF(enumFoo)
GETENUM_DEF(enumHehe)
int main() {
std::cout<<get_enumFoo<foo>::value()<<std::endl; //returns 0;
std::cout<<get_enumFoo<bar>::value()<<std::endl; //returns -1;
std::cout<<get_enumHehe<foo>::value()<<std::endl; //returns 1;
std::cout<<get_enumHehe<bar>::value()<<std::endl; //returns 2;
return 0;
}