Skip to content

Instantly share code, notes, and snippets.

@hare1039
Last active October 8, 2019 14:41
Show Gist options
  • Save hare1039/581b20cc8fbc8058d875894f05e655e5 to your computer and use it in GitHub Desktop.
Save hare1039/581b20cc8fbc8058d875894f05e655e5 to your computer and use it in GitHub Desktop.
A string switch impl in c++
#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