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

后端 未结 13 1763
长情又很酷
长情又很酷 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 01:50

    There is another way that doesn’t rely on line counts or templates. The only requirement is sticking the enum values in their own file and making the preprocessor/compiler do the count like so:

    my_enum_inc.h

    ENUMVAL(BANANA)
    ENUMVAL(ORANGE=10)
    ENUMVAL(KIWI)
    ...
    #undef ENUMVAL
    

    my_enum.h

    typedef enum {
      #define ENUMVAL(TYPE) TYPE,
      #include "my_enum_inc.h"
    } Fruits;
    
    #define ENUMVAL(TYPE) +1
    const size_t num_fruits =
      #include "my_enum_inc.h"
      ;
    

    This allows you to put comments with the enum values, re-assign values and does not inject an invalid 'count' enum value that needs to be ignored/accounted for in code.

    If you don't care about comments you don't need an extra file and can do as someone above mentioned, e.g.:

    #define MY_ENUM_LIST \
        ENUMVAL(BANANA) \
        ENUMVAL(ORANGE = 7) \
        ENUMVAL(KIWI)
    

    and replace the #include "my_enum_inc.h" directives with MY_ENUM_LIST but you'll need to #undef ENUMVAL after each use.

提交回复
热议问题