#include <unordered_map>
#include <functional>
#include <string>
#include <cstdio>
template <typename T>
class Switch
{
private:
T expression;
std::unordered_map<T, std::function<void()>> map;
std::function<void()> defaultFunction;
public:
Switch(const T& v) { this->expression = v; }
Switch& case_(const T& c, const std::function<void()>& f) {
map[c] = f;
return *this;
}
Switch& default_(const std::function<void()>& f) {
this->defaultFunction = f;
return *this;
}
virtual ~Switch() {
if (map[expression]) {
map[expression]();
} else {
defaultFunction();
}
}
};
int main(int argc, char* argv[])
{
if (argc < 2) {
return 1;
}
std::string v(argv[1]);
Switch<std::string>(v)
.case_("hello", [] { std::printf("get hello\n"); })
.case_("world", [] { std::printf("get world\n"); })
.default_([] { std::printf("get other string\n"); });
Switch<int>(argc)
.default_([=] { std::printf("get %d args\n", argc); });
return 0;
}