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

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

    It can be solved by a trick with std::initializer_list:

    #define TypedEnum(Name, Type, ...)                                \
    struct Name {                                                     \
        enum : Type{                                                  \
            __VA_ARGS__                                               \
        };                                                            \
        static inline const size_t count = []{                        \
            static Type __VA_ARGS__; return std::size({__VA_ARGS__}); \
        }();                                                          \
    };
    

    Usage:

    #define Enum(Name, ...) TypedEnum(Name, int, _VA_ARGS_)
    Enum(FakeEnum, A = 1, B = 0, C)
    
    int main()
    {
        std::cout << FakeEnum::A     << std::endl
                  << FakeEnun::count << std::endl;
    }
    

提交回复
热议问题