C++ string to enum

前端 未结 12 1238
无人及你
无人及你 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:34

    "Additional question: Is it possibile to handle undefined strings ? I mean if I try to get the value for responseHeaderMap["cookie"], what will be the value? (provided that "cookie" is not defined in the responseHeaderMap – bart s Nov 22 '16 at 12:04"

    well, you can just make check before:

    auto it = responseHeaderMap.find("cookie");
    if (it != responseHeaderMap.end())
    {
         // "cookie" exist, can take value 
    }
    

    After "cookie" exist check, you can get it value with use:

    responseHeaderMap["cookie"]
    

    hope this help

    0 讨论(0)
  • 2020-11-29 12:39

    You can use macro to minimize repeating yourself. Here is the trick: Enums, Macros, Unicode and Token-Pasting

    0 讨论(0)
  • 2020-11-29 12:42

    While there is no direct solution, there are a few possible workarounds.

    Take a look at this question: Easy way to use variables of enum types as string in C?

    0 讨论(0)
  • 2020-11-29 12:45

    this worked for me:

    enum NODES { Cone = 1, BaseColor = 2, NONE = 0 };
    
    std::map<std::string, NODES> nodeMap;
    nodeMap["Cone"] = NODES::Cone;
    nodeMap["BaseColor"] = NODES::BaseColor;
    
    0 讨论(0)
  • 2020-11-29 12:49

    It is not possible because the names are not available at runtime. During compilation each enum is replaced with the corresponding integer value.

    0 讨论(0)
  • 2020-11-29 12:51

    No, you'll have to use an if/then construction, or use a map or hash table or some other type of associative data structure to facilitate this.

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