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

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

    There is one trick based on X()-macros: image, you have the following enum:

    enum MyEnum {BOX, RECT};
    

    Reformat it to:

    #define MyEnumDef \
        X(BOX), \
        X(RECT)
    

    Then the following code defines enum type:

    enum MyEnum
    {
    #define X(val) val
        MyEnumDef
    #undef X
    };
    

    And the following code calculates number of enum elements:

    template  void null(T...) {}
    
    template 
    constexpr size_t countLength(T ... args)
    {
        null(args...); //kill warnings
        return sizeof...(args);
    }
    
    constexpr size_t enumLength()
    {
    #define XValue(val) #val
        return countLength(MyEnumDef);
    #undef XValue
    }
    
    ...
    std::array some_arr; //enumLength() is compile-time
    std::cout << enumLength() << std::endl; //result is: 2
    ...
    

提交回复
热议问题