Is it possible to determine the cardinality of a c++ enum class:
enum class Example { A, B, C, D, E };
I tried to use si
There is one trick based on X()-macros: image, you have the following enum:
enum MyEnum {BOX, RECT};
Reformat it to:
#define MyEnumDef \
X(BOX), \
X(RECT)
Then the following code defines enum type:
enum MyEnum
{
#define X(val) val
MyEnumDef
#undef X
};
And the following code calculates number of enum elements:
template void null(T...) {}
template
constexpr size_t countLength(T ... args)
{
null(args...); //kill warnings
return sizeof...(args);
}
constexpr size_t enumLength()
{
#define XValue(val) #val
return countLength(MyEnumDef);
#undef XValue
}
...
std::array some_arr; //enumLength() is compile-time
std::cout << enumLength() << std::endl; //result is: 2
...