Was thinking about extending the C switch beyond integers. Here is what it came to - will gladly accept any suggestions for improvement. Note: "Any class" in the title is not quite correct - the class should have equal operator and hash function to be used in this switch.
#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>
template<typename T>
using xmap = std::unordered_map<T, std::function<void()>>;
template<typename T>
void xwitch(const T& var, const xmap<T>& m, std::function<void()> otherwise = []() {})
{
auto it = m.find(var);
if (it == m.end())
otherwise();
else
it->second();
}
#define SWITCH(var) xwitch(var, xmap<std::remove_const<decltype(str)>::type> {
#define END_SWITCH });
#define CASE {
#define THEN , []() {
#define END_CASE } },
#define DEFAULT }, []() {
int main()
{
const std::string str{ "Second string" };
using namespace std::string_literals;
SWITCH(str)
CASE "First string"s THEN std::cout << "First string matched\n"; END_CASE
CASE "Second string"s THEN std::cout << "Second string matched\n"; END_CASE
CASE "Third string"s THEN std::cout << "Third string matched\n"; END_CASE
END_SWITCH
SWITCH("unmatched"s)
CASE "First string"s THEN std::cout << "First string matched\n"; END_CASE
CASE "Second string"s THEN std::cout << "Second string matched\n"; END_CASE
CASE "Third string"s THEN std::cout << "Third string matched\n"; END_CASE
DEFAULT std::cout << "No matches\n";
END_SWITCH
}
operator==andstd::hash<T>(...). But your question is valid regardless. \$\endgroup\$