Function, lambda, and switching on strings

In the same spirit as that of my last post, I found myself needing to compare strings that my hobby project is receiving on command line arguments and to take specific actions based on what was passed.

The usual if-else statement felt like a lot of typing and I thought why not just use lambdas to dictate what needs to be done and use the unordered_map to match the string and execute the appropriate lambda.

Ergo, I got started on this task. I know I need a hash map of a sort and although in C++, keys don’t need to be string, given my current needs, I went with std::string. Now, there is the question of how to associate the lambdas as values, and that’s where std::function comes into play.

Encapsulating the behavior

I also want to tie everything together, So I went with a struct.

Now comes the part of populating the hash map and that’s below:

Now, I want to be able to just do this and execute the correct flow:

For that, I’m going to overload the call operator and have it take the key as an input parameter:

Now, I have two tasks, check if the key exists, if it does execute the function associated with it. If not, check if any key is set for ‘default’ case (because why not), otherwise for the time being, just print an error. I could later in the future, throw an exception, in such a situation.

Using the string switcher

Okay, with that much done so far. I could, for example, use this struct as follows:

Output for that would be:

In my hobby project, I collapsed the if-else-if as follows:

Software Developer

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