Last active
June 10, 2017 04:55
-
-
Save dongho-jung/abd770a8a07cddedf3f633164e2e1640 to your computer and use it in GitHub Desktop.
It makes switch be able to treat string.
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
// Hash function by http://blog.naver.com/PostView.nhn?blogId=devmachine&logNo=220952781191 | |
// Hash const by http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&pageno=0&detail=1&wid=1223 | |
#include <iostream> | |
using namespace std; | |
constexpr unsigned int HashCode(const char* str) { | |
return str[0] ? static_cast<unsigned int>(str[0]) + 0xEDB8832Full * HashCode(str + 1) : 8603; | |
} | |
#define STRING_SWITCH_START(x) {string _SWITCHx_ = x; switch(HashCode(x.c_str())) | |
#define S_CASE_START(x) case HashCode(x): if (_SWITCHx_ == x) { | |
#define S_CASE_END } else { throw logic_error("[!] Error. Hash collision!"); } break | |
#define STRING_SWITCH_END } | |
int main() { | |
string test = "bye"; | |
STRING_SWITCH_START(test) { | |
S_CASE_START("hello") cout << "Hello World." << endl; S_CASE_END; | |
S_CASE_START("bye") cout << "Bye Bye~" << endl; S_CASE_END; | |
S_CASE_START("apple") cout << "Apple is fresh." << endl; S_CASE_END; | |
S_CASE_START("orange") cout << "Orange is sour." << endl; S_CASE_END; | |
S_CASE_START("melon") cout << "Melon is sweet." << endl; S_CASE_END; | |
}STRING_SWITCH_END; | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment