C++ string to enum

前端 未结 12 1237
无人及你
无人及你 2020-11-29 12:01

Is there a simple way in C++ to convert a string to an enum (similar to Enum.Parse in C#)? A switch statement would be very long, so I was wondering i

相关标签:
12条回答
  • 2020-11-29 12:26

    saw this example somewhere

    #include <map>
    #include <string>
    
    enum responseHeaders
    {
        CONTENT_ENCODING,
        CONTENT_LENGTH,
        TRANSFER_ENCODING,
    };
    
    // String switch paridgam   
    struct responseHeaderMap : public std::map<std::string, responseHeaders>
    {
        responseHeaderMap()
        {
            this->operator[]("content-encoding") =  CONTENT_ENCODING;
            this->operator[]("content-length") = CONTENT_LENGTH;
            this->operator[]("transfer-encoding") = TRANSFER_ENCODING;
        };
        ~responseHeaderMap(){}
    };
    
    0 讨论(0)
  • 2020-11-29 12:28

    There is no "built-in way", but there are ways to achieve this by storing the pair value-name in an array

    enum myEnum
    {
        enumItem0,
        enumItem1,
        enumItem7 = 7,
        enumItem8
    };
    
    std::vector<std::pair<myEnum,std::string>>   gMap;
    
    #define ADDITEM(x)  gMap.push_back(std::pair<myEnum,std::string>(x,#x));
    

    .....

    ADDITEM(enumItem0);
    ADDITEM(enumItem1);
    ADDITEM(enumItem7);
    ADDITEM(enumItem8);
    
    0 讨论(0)
  • 2020-11-29 12:30

    Use std::map<std::string, Enum> and use boost::map_list_of to easily initialize it.

    Example,

    enum X
    {
       A,
       B,
       C
    };
    
    std::map<std::string, X> xmap = boost::map_list_of("A", A)("B", B)("C",C);
    
    0 讨论(0)
  • 2020-11-29 12:31

    A std::map<std::string, MyEnum> (or unordered_map) could do it easily. Populating the map would be just as tedious as the switch statement though.

    Edit: Since C++11, populating is trivial:

    static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} };
    auto it = table.find(str);
    if (it != table.end()) {
      return it->second;
    } else { error() }
    
    0 讨论(0)
  • 2020-11-29 12:34

    I use this "trick" > http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C

    After

    enum FORM {
        F_NONE = 0,
        F_BOX,
        F_CUBE,
        F_SPHERE,
    };
    

    insert

    Begin_Enum_String( FORM )
    {
        Enum_String( F_NONE );
        Enum_String( F_BOX );
        Enum_String( F_CUBE );
        Enum_String( F_SPHERE );
    }
    End_Enum_String;
    

    It works fine, if the values in the enum are not duplicates.

    Example in code

    enum FORM f = ...
    const std::string& str = EnumString< FORM >::From( f );
    

    vice versa

    assert( EnumString< FORM >::To( f, str ) );
    
    0 讨论(0)
  • 2020-11-29 12:34

    In short: there is none. In C++ enums are static values and not objects like in C#. I suggest you use a function with some if else statements.

    0 讨论(0)
提交回复
热议问题