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

后端 未结 30 2811
我在风中等你
我在风中等你 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 11:03

    I have an incredibly simple to use macro that does this in a completely DRY fashion. It involves variadic macros and some simple parsing magic. Here goes:

    #define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \
    inline std::ostream& operator<<(std::ostream& os, name value) { \
    std::string enumName = #name; \
    std::string str = #__VA_ARGS__; \
    int len = str.length(); \
    std::vector strings; \
    std::ostringstream temp; \
    for(int i = 0; i < len; i ++) { \
    if(isspace(str[i])) continue; \
            else if(str[i] == ',') { \
            strings.push_back(temp.str()); \
            temp.str(std::string());\
            } \
            else temp<< str[i]; \
    } \
    strings.push_back(temp.str()); \
    os << enumName << "::" << strings[static_cast(value)]; \
    return os;} 
    

    To use this in your code, simply do:

    AWESOME_MAKE_ENUM(Animal,
        DOG,
        CAT,
        HORSE
    );
    

提交回复
热议问题