Last active
July 29, 2021 02:15
-
-
Save Liam0205/25dcb10e55b3cb2306931aa277355bbf to your computer and use it in GitHub Desktop.
Apply C style string in switch-case clause in C++. (C++11 or above required)
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> | |
#include <string> | |
using hash_t = size_t; | |
constexpr hash_t prime = 0x100000001B3ull; | |
constexpr hash_t basis = 0xCBF29CE484222325ull; | |
hash_t hash_run_time(const char* str) { | |
hash_t ret = basis; | |
while (*str) { | |
ret ^= *str; | |
ret *= prime; | |
str++; | |
} | |
return ret; | |
} | |
constexpr hash_t hash_compile_time(const char* str, hash_t last_value = basis) { | |
return *str ? hash_compile_time(str + 1, (*str ^ last_value) * prime) : last_value; | |
} | |
constexpr hash_t operator "" _hash(const char* p, size_t) { | |
return hash_compile_time(p); | |
} | |
void simple_switch(const char* str) { | |
switch (hash_run_time(str)) { | |
case "first"_hash: | |
std::cout << "1st" << std::endl; | |
break; | |
case "second"_hash: | |
std::cout << "2nd" << std::endl; | |
break; | |
case "third"_hash: | |
std::cout << "3rd" << std::endl; | |
break; | |
default: | |
std::cout << "Default..." << std::endl; | |
} | |
} | |
int main() { | |
std::string str = "first"; | |
simple_switch(str.c_str()); | |
simple_switch("second"); | |
str = "third"; | |
simple_switch(str.c_str()); | |
simple_switch("default"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment