Is there a simple way to convert C++ enum to string?

后端 未结 30 2803
我在风中等你
我在风中等你 2020-11-22 10:37

Suppose we have some named enums:

enum MyEnum {
      FOO,
      BAR = 0x50
};

What I googled for is a script (any language) that scans all

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 10:55

    Here a one-file solution (based on elegant answer by @Marcin:

    #include 
    
    #define ENUM_TXT \
    X(Red) \
    X(Green) \
    X(Blue) \
    X(Cyan) \
    X(Yellow) \
    X(Magenta) \
    
    enum Colours {
    #   define X(a) a,
    ENUM_TXT
    #   undef X
        ColoursCount
    };
    
    char const* const colours_str[] = {
    #   define X(a) #a,
    ENUM_TXT
    #   undef X
        0
    };
    
    std::ostream& operator<<(std::ostream& os, enum Colours c)
    {
        if (c >= ColoursCount || c < 0) return os << "???";
        return os << colours_str[c] << std::endl;
    }
    
    int main()
    {
        std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;
    }
    

提交回复
热议问题