Enum to string in C++11

后端 未结 6 1833
囚心锁ツ
囚心锁ツ 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条回答
  •  猫巷女王i
    2021-02-03 22:18

    Here is a simple example using namespaces and structs. A class is created for each enum item. In this example i chose int as the type for the id.

    #include 
    using namespace std;
    
    #define ENUMITEM(Id, Name) \
    struct Name {\
        static constexpr const int id = Id;\
        static constexpr const char* name = #Name;\
    };
    
    namespace Food {
    ENUMITEM(1, Banana)
    ENUMITEM(2, Apple)
    ENUMITEM(3, Orange)
    }
    
    int main() {
        cout << Food::Orange::id << ":" << Food::Orange::name << endl;
        return 0;
    }
    

    Output:

    3:Orange
    

    == Update ==

    Using:

    #define STARTENUM() constexpr const int enumStart = __LINE__;
    #define ENUMITEM(Name) \
    struct Name {\
        static constexpr const int id = __LINE__ - enumStart - 1;\
        static constexpr const char* name = #Name;\
    };
    

    and using it once before the first usage of ENUMITEM the ids would not be needed anymore.

    namespace Food {
    STARTENUM()
    ENUMITEM(Banana)
    ENUMITEM(Apple)
    ENUMITEM(Orange)
    }
    

    The variable enumStart is only accessible through the namespace - so still multiple enums can be used.

提交回复
热议问题