Last active
February 5, 2020 17:51
-
-
Save KaiserKatze/7996f518f37392fbdf54d10ef9182004 to your computer and use it in GitHub Desktop.
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
// Question: | |
// @see: https://stackoverflow.com/questions/650162/why-the-switch-statement-cannot-be-applied-on-strings | |
// | |
// Solution: | |
// @see: https://blog.csdn.net/yozidream/article/details/22789147 | |
#include <iostream> | |
namespace SimpleHash | |
{ | |
using hash_t = std::uint64_t; | |
constexpr static hash_t prime{ 0x100000001B3ull }; | |
constexpr static hash_t basis{ 0xCBF29CE484222325ull }; | |
// C++11 constexpr functions use recursion rather than iteration | |
// (C++14 constexpr functions may use local variables and loops) | |
// | |
// The parameter cannot have non-literal-type, | |
// which means `std::string` cannot be | |
// declared as the parameter. | |
// | |
// @see: https://en.cppreference.com/w/cpp/language/constexpr | |
constexpr hash_t hash(const char* str) | |
{ | |
hash_t ret{ basis }; | |
while (*str) | |
{ | |
ret ^= *str; | |
ret *= prime; | |
str++; | |
} | |
return ret; | |
} | |
constexpr hash_t operator "" h(const char* s, size_t) | |
{ | |
return hash(s); | |
} | |
}; | |
void TestSwitch(const char* s); | |
int main() | |
{ | |
std::string messages[] = { | |
"Alpha", "Nothing", "Beta", "Now" | |
}; | |
for (const std::string& message : messages) | |
{ | |
TestSwitch(message.c_str()); | |
} | |
// Expected output: | |
// Alpha | |
// Default | |
// Beta | |
// Default | |
return 0; | |
} | |
void TestSwitch(const char* s) | |
{ | |
using namespace SimpleHash; // !!! IMPORTANT !!! | |
switch (hash(s)) | |
{ | |
case "Alpha"h: | |
std::cout << "Alpha" << std::endl; | |
break; | |
case "Beta"h: | |
std::cout << "Beta" << std::endl; | |
break; | |
default: | |
std::cout << "Default" << std::endl; | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment