Is it possible to determine the number of elements of a c++ enum class?

Not directly, but you could use the following trick:

enum class Example { A, B, C, D, E, Count };

Then the cardinality is available as static_cast<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:

enum class Example { A = 1, B = 2, C = 4, D = 8, E = 16, Count = 5 };

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.)


For C++17 you can use magic_enum::enum_count from lib https://github.com/Neargye/magic_enum:

magic_enum::enum_count<Example>() -> 4.

Where is the drawback?

This library uses a compiler-specific hack (based on __PRETTY_FUNCTION__ / __FUNCSIG__), which works on Clang >= 5, MSVC >= 15.3 and GCC >= 9.

We go through the given interval range, and find all the enumerations with a name, this will be their count. Read more about limitations

Many more about this hack in this post https://taylorconor.com/blog/enum-reflection.