NOTE: This is not about using a string for choosing the execution path in a switch-case block.
A common pattern in C++ is to use a switch-case block for converting integer constants to strings. This looks like:
char const * to_string(codes code)
{
switch (code)
{
case codes::foo: return "foo";
case codes::bar: return "bar";
}
}
However, we are in C++, so using std::string is more appropriate:
std::string to_string(codes code)
{
switch (code)
{
case codes::foo: return "foo";
case codes::bar: return "bar";
}
}
This however copies the string literal. Perhaps a better approach would be instead:
std::string const & to_string(codes code)
{
switch (code)
{
case codes::foo: { static std::string str = "foo"; return str; }
case codes::bar: { static std::string str = "bar"; return str; }
}
}
But this is kinda ugly, and involves more boilerplate.
What is considered the cleanest and most efficient solution for this problem using C++14?