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

后端 未结 28 2227
逝去的感伤
逝去的感伤 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:32

    The following solution is based on a std::array for a given enum.

    For enum to std::string conversion we can just cast the enum to size_t and lookup the string from the array. The operation is O(1) and requires no heap allocation.

    #include 
    #include 
    #include 
    
    #include 
    #include 
    #include 
    
    #define STRINGIZE(s, data, elem) BOOST_PP_STRINGIZE(elem)
    
    // ENUM
    // ============================================================================
    #define ENUM(X, SEQ) \
    struct X {   \
        enum Enum {BOOST_PP_SEQ_ENUM(SEQ)}; \
        static const std::array array_of_strings() { \
            return {{BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(STRINGIZE, 0, SEQ))}}; \
        } \
        static std::string to_string(Enum e) { \
            auto a = array_of_strings(); \
            return a[static_cast(e)]; \
        } \
    }
    

    For std::string to enum conversion we would have to make a linear search over the array and cast the array index to enum.

    Try it here with usage examples: http://coliru.stacked-crooked.com/a/e4212f93bee65076

    Edit: Reworked my solution so the custom Enum can be used inside a class.

提交回复
热议问题