Enum to string in C++11

后端 未结 6 1807
囚心锁ツ
囚心锁ツ 2021-02-03 21:52

I realize this has been asked before more than once on SO but I couldn\'t find a question explicitly looking for a current solution to this issue with C++11, so here we go again

6条回答
  •  隐瞒了意图╮
    2021-02-03 22:39

    You can use macro to solve this problem:

    #define MAKE_ENUM(name, ...) enum class name { __VA_ARGS__}; \
    static std::vector Enum_##name##_init(){\
        const std::string content = #__VA_ARGS__; \
        std::vector str;\
        size_t len = content.length();\
        std::ostringstream temp;\
        for(size_t i = 0; i < len; i ++) {\
        if(isspace(content[i])) continue;\
        else if(content[i] == ',') {\
        str.push_back(temp.str());\
        temp.str(std::string());}\
        else temp<< content[i];}\
        str.push_back(temp.str());\
        return str;}\
    static const std::vector Enum_##name##_str_vec = Enum_##name##_init();\
    static std::string to_string(name val){\
        return Enum_##name##_str_vec[static_cast(val)];\
    }\
    static std::string print_all_##name##_enum(){\
        int count = 0;\
        std::string ans;\
        for(auto& item:Enum_##name##_str_vec)\
        ans += std::to_string(count++) + ':' + item + '\n';\
        return ans;\
    }
    

    As the static variable can only be initialized once, so the Enum_##name##_str_vec will use the Enum_##name##_init() function to initialize itself at first.

    The sample code is as below:

    MAKE_ENUM(Analysis_Time_Type,
                      UNKNOWN,
                      REAL_TIME, 
                      CLOSSING_TIME 
    );
    

    Then you can use below sentence to print an enum value:

    to_string(Analysis_Time_Type::UNKNOWN)
    

    And use below sentence to print all enum as string:

    print_all_Analysis_Time_Type_enum()
    

提交回复
热议问题