Is it possible to determine the cardinality of a c++ enum class
:
enum class Example { A, B, C, D, E };
I tried to use sizeof
, however, it returns the size of an enum element.
sizeof(Example); // Returns 4 (on my architecture)
Is there a standard way to get the cardinality (5 in my example) ?
No , you have to write it in the code.
There is one trick based on X()-macros: image, you have the following enum:
Reformat it to:
Then the following code defines enum type:
And the following code calculates number of enum elements:
One trick you can try is to add a enum value at the end of your list and use that as the size. In your example
Not directly, but you could use the following trick:
Then the cardinality is available as
(int)Example::Count
.Of course, this only works nicely if you let values of the enum be automatically assigned, starting from 0. If that's not the case, you can manually assign the correct cardinality to Count, which is really no different from having to maintain a separate constant anyway:
The one disadvantage is that the compiler will allow you to use
Example::Count
as an argument for an enum value -- so be careful if you use this! (I personally find this not to be a problem in practice, though.)This is derived from UglyCoder's answer but improves it in three ways.
BEGIN
andSIZE
) (Cameron's answer also has this problem.)It retains UglyCoder's advantage over Cameron's answer that enumerators can be assigned arbitrary values.
A problem (shared with UglyCoder but not with Cameron) is that it makes newlines and comments significant ... which is unexpected. So someone could add an entry with whitespace or a comment without adjusting
TEST_SIZE
's calculation.