Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply C style string in switch-case clause in C++. (C++11 or above required)
#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
You can’t perform that action at this time.