Last active
October 8, 2019 14:41
-
-
Save hare1039/581b20cc8fbc8058d875894f05e655e5 to your computer and use it in GitHub Desktop.
A string switch impl in c++
This file contains 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
#include <iostream> | |
// based on https://stackoverflow.com/a/46711735/5921729 | |
constexpr inline | |
long long int hash(char const * str, int h = 0) | |
{ | |
return (!str[h] ? 5381 : (hash(str, h+1)*33) ^ str[h] ); | |
} | |
constexpr inline | |
long long int operator "" _(char const * p, size_t) { return hash(p); } | |
inline | |
long long int hash(std::string const & s) { return hash (s.c_str()); } | |
int main() | |
{ | |
std::string cat{"Peter"}; | |
switch (hash(cat)) | |
{ | |
case "Peter"_: | |
{ | |
std::cout << "Cat's name is Peter\n"; | |
break; | |
} | |
case "Jacky"_: | |
{ | |
std::cout << "Cat's name is Jacky\n"; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment