C++ string to enum
Solution 1:
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() }
Solution 2:
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);
Solution 3:
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(){}
};