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
"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
You can use macro to minimize repeating yourself. Here is the trick: Enums, Macros, Unicode and Token-Pasting
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?
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;
It is not possible because the names are not available at runtime. During compilation each enum is replaced with the corresponding integer value.
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.