Last active
June 15, 2020 05:07
-
-
Save BtheDestroyer/67fd5c2497953a4d3a1be317db9f833f to your computer and use it in GitHub Desktop.
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
// This file is to showcase the use of the relatively new constexpr keyword to | |
// allow for processing of C-style strings at compile time. | |
// In turn, this allows for the use of C-style strings as cases in a switch | |
// statement. This is something that is typically impossible as C-style strings | |
// effectively degrade into void* in this situation as no string comparison | |
// is normally possible. | |
// An example of why this would be useful would be in an assembler or other | |
// simple language interpreter to improve interpretation time from O(n) | |
// in an if {} else if {} chain to O(log(n)). | |
// Another benefit over using enums is the lowered reliance on consistancy across | |
// multiple files. With this solution, enum definitions need not be created | |
// updated to reflect the use in functions. | |
// A tradeoff, however, is the lack of transparancy. This can be positive or | |
// negative, depending on the circumstance; an open-source project might require | |
// more descriptive documentation to be available, but closed-source distributables | |
// could keep more of their inner-workings private. | |
#include <iostream> | |
#include <string> | |
typedef char byte; | |
constexpr unsigned long long hashString(const byte* str) | |
{ | |
unsigned long long r = 1435958502956573194; | |
// sdbm | |
while (*str) | |
r = *str++ + (r << 6) + (r << 16) - r; | |
return r; | |
} | |
unsigned long long hashString(const std::string& str) | |
{ | |
return hashString(str.c_str()); | |
} | |
int main() | |
{ | |
std::string input; | |
std::cout << "Input string: "; | |
std::cin >> input; | |
std::cout << "You gave me: " << input << std::endl; | |
std::cout << "Hash: " << hashString(input) << std::endl; | |
switch (hashString(input)) | |
{ | |
case hashString("Hello"): | |
std::cout << "Well, hi!" << std::endl; | |
break; | |
case hashString("Bye"): | |
std::cout << "Oh, ok..." << std::endl; | |
break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment