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...