Last active
January 17, 2024 02:19
-
-
Save Gnomorian/96c9482fd7058309f15a45554726aa66 to your computer and use it in GitHub Desktop.
A Hacky way to use strings in switch statements c++
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 <array> | |
template<size_t NumOfStrings> | |
struct StringToInt | |
{ | |
std::array<std::string_view, NumOfStrings> strings{}; | |
constexpr StringToInt(auto&&...args) | |
{ | |
auto addEntry = [](auto&& collection, auto&& argument, size_t i) | |
{ | |
collection[i] = argument; | |
}; | |
int i = 0; | |
((addEntry(strings, args, i++)),...); | |
} | |
constexpr size_t operator[] (std::string_view str) const | |
{ | |
for (size_t i = 0; i < strings.size(); i++) | |
{ | |
if (str == strings[i]) | |
return i; | |
} | |
return -1; // not found, so use default: case in a switch | |
} | |
}; | |
constexpr auto make_string_to_int(auto&&...args) | |
{ | |
StringToInt<sizeof...(args)> stoint(args...); | |
return stoint; | |
} | |
int main() | |
{ | |
constexpr auto TheString{ "Something" }; | |
constexpr auto something{ make_string_to_int("Hello, World", TheString) }; | |
switch (something[TheString]) | |
{ | |
case something["Hello, World"]: | |
std::cout << "Hello, World" << std::endl; | |
break; | |
case something[TheString]: | |
std::cout << TheString << std::endl; | |
break; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it works by compile time creating a structure that contains the possible strings in the switch statement that are contained in an array.
StringToInt["string"] returns the index to that string in the array.