I am trying to return an enum based on a string value (the string is from a json file, if it matters)
Basically, where in code I would write enumName::MyName
, I want to be able to have something like
std::string name = "MyName";
return enumName::name; // this gets converted to enumName::MyName
Obviously that's incorrect syntax. I had the idea of using macros to solve my problem, so here's my current attempt:
#define stringToName(n) enumName::##n
Where I used the ##
token pasting operator. But in that case, n
isn't evaluated before being copied, so the following thing happens
return stringToName("MyName");
//which becomes
return enumName::"MyName";
Or
std::string name = "MyName";
return stringToName(name);
//which becomes
return enumName::name;
And that's not quite what I want. Is there a way to make it work? (Ideally without having to write each and every enum name manually in a dictionary or something like that)