Use mapped lambdas for a jump table
A jump table is a useful pattern when you want to select an action from a user or other input. Jump tables are often implemented in if/else or switch structures. In this recipe, we'll build a concise jump table using only an STL map and anonymous lambdas.
How to do it…
It's easy to build a simple jump table from a map and lambdas. The map provides simple indexed navigation and the lambda can be stored as payload. Here's how to do it:
- First, we'll create a simple
prompt()function to get input from the console:const char prompt(const char * p) { Â Â Â Â std::string r; Â Â Â Â cout << format("{} > ", p); Â Â Â Â std::getline(cin, r, '\n'); Â Â Â Â if(r.size() < 1) return '\0'; Â Â Â Â if(r.size() > 1) { Â Â Â Â Â Â Â Â cout << "Response too long...