Function, lambda, and switching on strings

Encapsulating the behavior

struct Switch {
using void_function = std::function<void(void)>;
std::unordered_map<std::string, void_function> cases;
...
Switch() {}
};
void add_case(std::string const & key, void_function func) {
cases[key] = func;
}
Switch s;
// adding some cases
...
s(to_switch_on)
void operator()(std::string const & key) {
...
}
void operator()(std::string const & key) {
auto f = cases.find(key);
f = (f == cases.end()) ? cases.find("default") : f;
if (f == cases.end()) {
std::cout << "Case not found and default not set\n";
return;
}
f->second();
}

Using the string switcher

std::string message = "c'est la vie";Switch s;
s.add_case("", [&message](void) {
std::cout << message << std::endl;
});

s.add_case("d", [msg="cogito ergo sum"]{
cout << msg << endl;
});
s("live_your_life");
s("i_think_therefore_i_am");
s("not_existing_key");
c'est la vie
cogito ergo sum
Defaul switch case
Switch s;
s.add_case("projects",[&]{this->showProjects();});
s.add_case("add", [&]{this->addProjects(arguments); });
s.add_case("latest", [&]{this->showLatest(arguments)});
s.add_case("time", [&]{this>startTimer(arguments)});
s.add_case("stop", [&]{this->stopTimer(arguments); });
s.add_case("today", [&]{this->showTimeSpentToday(arguments);});
s(command);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store