Count on enum C++ automatic

后端 未结 5 1902
北荒
北荒 2020-12-10 09:27

I\'ve come to a pattern when writing enums in C++. It is like this:

class Player
{
public:
    class State
    {
    public:
        typedef enum
        {
          


        
5条回答
  •  情深已故
    2020-12-10 09:49

    The solution stackoverflow.com/a/60216003/12894563 can be improved. We can save enums expressions in a static vector and iterate, obtain min/max and etc

    Usage:

    #include 
    #include 
    #include 
    #include 
    
    #define make_enum(Name, Type,  ...)                                              \
        struct Name {                                                                \
            enum : Type {                                                            \
                __VA_ARGS__                                                          \
            };                                                                       \
            static auto count() { return values.size(); }                            \
                                                                                     \
            static inline const std::vector values = [] {                      \
                static Type __VA_ARGS__; return std::vector({__VA_ARGS__});    \
            }();                                                                     \
            static Type min()                                                        \
            {                                                                        \
                static const Type result = *std::min_element(values.begin(), values.end()); \
                return result;                                                       \
            }                                                                        \
            static Type max()                                                        \
            {                                                                        \
                static const Type result = *std::max_element(values.begin(), values.end()); \
                return result;                                                       \
            }                                                                        \
    }
    
    
    
    make_enum(FakeEnum, int, A = 1, B = 0, C = 2, D);
    
    int main(int argc, char *argv[])
    {
        std::cout << FakeEnum::A     << std::endl
                  << FakeEnum::min() << std::endl
                  << FakeEnum::max() << std::endl
                  << FakeEnum::count() << std::endl;
        return 0;
    }
    

提交回复
热议问题