You'll need to use an if-else-if
ladder or use a table.
if-else-if ladder:
if (text == "apple")
{
Eat_Apple();
}
else if (text == "steak")
{
Eat_Steak();
}
else
{
Starve();
}
You may want to transform
the string into all lower case or all upper case before comparing.
Maps of function pointers
An alternative is to use std::map
with function pointers or function objects.
typedef void (*Function_Pointer)(); // Synonym for function pointer.
std::map<std::string, Function_Pointer> database;
//...
database["apple"] = Eat_An_Apple;
database["steak"] = Eat_A_Steak;
std::map<std::string, Function_Pointer>::iterator iter = database.find(text);
if (iter != database.end())
{
(*iter)(); // Execute via the function pointer.
}
else
{
Starve();
}
The Table
A third alternative is to use a table of pairs, where the value is the function pointer.
struct Entry
{
std::string name;
Function_Pointer function;
};
static const Entry database[] =
{
{"apple", Eat_An_Apple},
{"steak", Eat_A_Steak},
};
static const unsigned int table_quantity =
sizeof(database) / sizeof(database[0]);
A nice attribute of the table is that it is constant data and initialized before the program starts. Technically, most compilers throw it into the data section or reference it in the data section. No time wasted initializing an ADT.