My ultimate goal is to achieve a mapping from a set of two character strings to corresponding data types:
"AA" --> char
"BB" --> int
"CC" --> float
"DD" --> std::complex<double>
and so on ...
The best "not quite working" solution I can come up with is two parts. The first part is using std::map to map between the strings and corresponding enum values. The second part uses a templated type alias and std::conditional to map the enum values to types.
enum class StrEnum { AA, BB, CC, DD };
// STEP 1: string --> enum
// !! std::map will not work here since a constexpr is required !!
std::map<std::string, StrEnum> str_map = {
{"AA", StrEnum::AA},
{"BB", StrEnum::BB},
{"CC", StrEnum::CC},
{"DD", StrEnum::DD}
};
// STEP 2: enum --> type
template<StrEnum val> using StrType = typename std::conditional<
val == StrEnum::AA,
char,
typename std::conditional<
val == StrEnum::BB,
int,
typename std::conditional<
val == StrEnum::CC,
float,
std::complex<double>
>::type
>::type
>::type;
Goal Usage:
StrType<str_map["BB"]> myVal; // <-- does not work in current state with std::map
As more value mappings are added the above nesting can get very nasty.
Is there a better/cleaner/working overall way to achieve this mapping? I'm especially interested in STEP 2 and whether there is a way to have less nesting.
I am using C++11. (but if the only answer lies in C++14 or beyond it would be nice to at least be aware of it)