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

后端 未结 13 1782
长情又很酷
长情又很酷 2020-12-13 01:39

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

13条回答
  •  遥遥无期
    2020-12-13 02:13

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

    magic_enum::enum_count() -> 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.

提交回复
热议问题