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

后端 未结 13 1806
长情又很酷
长情又很酷 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:12

    If you make use of boost's preprocessor utilities, you can obtain the count using BOOST_PP_SEQ_SIZE(...).

    For example, one could define the CREATE_ENUM macro as follows:

    #include 
    
    #define ENUM_PRIMITIVE_TYPE std::int32_t
    
    #define CREATE_ENUM(EnumType, enumValSeq)                                  \
    enum class EnumType : ENUM_PRIMITIVE_TYPE                                  \
    {                                                                          \
       BOOST_PP_SEQ_ENUM(enumValSeq)                                           \
    };                                                                         \
    static constexpr ENUM_PRIMITIVE_TYPE EnumType##Count =                     \
                     BOOST_PP_SEQ_SIZE(enumValSeq);                            \
    // END MACRO   
    

    Then, calling the macro:

    CREATE_ENUM(Example, (A)(B)(C)(D)(E));
    

    would generate the following code:

    enum class Example : std::int32_t 
    {
       A, B, C, D, E 
    };
    static constexpr std::int32_t ExampleCount = 5;
    

    This is only scratching the surface with regards to the boost preprocessor tools. For example, your macro could also define to/from string conversion utilities and ostream operators for your strongly typed enum.

    More on boost preprocessor tools here: https://www.boost.org/doc/libs/1_70_0/libs/preprocessor/doc/AppendixA-AnIntroductiontoPreprocessorMetaprogramming.html


    As an aside, I happen to strongly agree with @FantasticMrFox that the additional Count enumerated value employed in the accepted answer will create compiler warning headaches galore if using a switch statement. I find the unhandled case compiler warning quite useful for safer code maintenance, so I wouldn't want to undermine it.

提交回复
热议问题