Skip to content

Instantly share code, notes, and snippets.

@david7482
Last active December 14, 2023 21:09
Show Gist options
  • Save david7482/70924ba3cc2cbbbfb88e to your computer and use it in GitHub Desktop.
Save david7482/70924ba3cc2cbbbfb88e to your computer and use it in GitHub Desktop.
Use C++11's constexpr to achieve string switch
// http://stackoverflow.com/a/107657
constexpr unsigned long long int HashStringToInt(const char *str, unsigned long long int hash = 0)
{
return (*str == 0) ? hash : 101 * HashStringToInt(str + 1) + *str;
}
void simple_switch(const std::string &str)
{
switch (HashStringToInt(str.c_str()))
{
case HashStringToInt("first"):
std::cout << "first case" << std::endl;
break;
case SimpleStringToInt("second"):
std::cout << "second case" << std::endl;
break;
default:
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment