Skip to content

Instantly share code, notes, and snippets.

@Gnomorian
Last active January 17, 2024 02:19
Show Gist options
  • Save Gnomorian/96c9482fd7058309f15a45554726aa66 to your computer and use it in GitHub Desktop.
Save Gnomorian/96c9482fd7058309f15a45554726aa66 to your computer and use it in GitHub Desktop.
A Hacky way to use strings in switch statements c++
#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;
};
}
@Gnomorian
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment