Last active
December 14, 2023 21:09
-
-
Save david7482/70924ba3cc2cbbbfb88e to your computer and use it in GitHub Desktop.
Use C++11's constexpr to achieve string switch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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