enum to string in modern C++11 / C++14 / C++17 and future C++20

后端 未结 28 2250
逝去的感伤
逝去的感伤 2020-11-22 16:57

Contrary to all other similar questions, this question is about using the new C++ features.

  • 2008 c Is there a simple way to convert C++ enum to string?
  • <
28条回答
  •  不知归路
    2020-11-22 17:28

    Very simple solution with one big constraint: you can't assign custom values to enum values, but with the right regex, you could. you could also add a map to translate them back to enum values without much more effort:

    #include 
    #include 
    #include 
    #include 
    
    std::vector split(const std::string& s, 
                                   const std::regex& delim = std::regex(",\\s*"))
    {
        using namespace std;
        vector cont;
        copy(regex_token_iterator(s.begin(), s.end(), delim, -1), 
             regex_token_iterator(),
             back_inserter(cont));
        return cont;
    }
    
    #define EnumType(Type, ...)     enum class Type { __VA_ARGS__ }
    
    #define EnumStrings(Type, ...)  static const std::vector \
                                    Type##Strings = split(#__VA_ARGS__);
    
    #define EnumToString(Type, ...) EnumType(Type, __VA_ARGS__); \
                                    EnumStrings(Type, __VA_ARGS__)
    

    Usage example:

    EnumToString(MyEnum, Red, Green, Blue);
    

提交回复
热议问题