Is there a way to find the cardinality (size) of an enum in C++?
c++, enums, size
Solution
Nope.
If there were, you wouldn't see so much code like this:
enum E {
VALUE_BLAH,
VALUE_OTHERBLAH,
...
VALUE_FINALBLAH,
VALUE_COUNT
}
Note that this code is also a hint for a (nasty) solution -- if you add a final "guard" element, and don't explicitly state the values of the enum fields, then the last "COUNT" element will have the value you're looking for -- this happens because enum count is zero-based:
enum B {
ONE, // has value = 0
TWO, // has value = 1
THREE, // has value = 2
COUNT // has value = 3 - cardinality of enum without COUNT
}
Problem
Could one write a function that returns the number of elements in an enum? For example, say I have defined: ``` enum E {x, y, z}; ``` Then f(E) would return 3.