C++ string to enum
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);
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() }