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

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

    Interesting to see the number of ways. here's one i used a long time ago:

    in file myenummap.h:

    #include 
    #include 
    enum test{ one, two, three, five=5, six, seven };
    struct mymap : std::map
    {
      mymap()
      {
        this->operator[]( one ) = "ONE";
        this->operator[]( two ) = "TWO";
        this->operator[]( three ) = "THREE";
        this->operator[]( five ) = "FIVE";
        this->operator[]( six ) = "SIX";
        this->operator[]( seven ) = "SEVEN";
      };
      ~mymap(){};
    };
    

    in main.cpp

    #include "myenummap.h"
    
    ...
    mymap nummap;
    std::cout<< nummap[ one ] << std::endl;
    

    Its not const, but its convenient.

    Here's another way that uses C++11 features. This is const, doesn't inherit an STL container and is a little tidier:

    #include 
    #include 
    #include 
    #include 
    
    //These stay together and must be modified together
    enum test{ one, two, three, five=5, six, seven };
    std::string enum_to_str(test const& e)
    {
        typedef std::pair mapping;
        auto m = [](test const& e,std::string const& s){return mapping(static_cast(e),s);}; 
        std::vector const nummap = 
        { 
            m(one,"one"), 
            m(two,"two"), 
            m(three,"three"),
            m(five,"five"),
            m(six,"six"),
            m(seven,"seven"),
        };
        for(auto i  : nummap)
        {
            if(i.first==static_cast(e))
            {
                return i.second;
            }
        }
        return "";
    }
    
    int main()
    {
    //  std::cout<< enum_to_str( 46 ) << std::endl; //compilation will fail
        std::cout<< "Invalid enum to string : [" << enum_to_str( test(46) ) << "]"<

提交回复
热议问题