I\'m trying to create a map of string and method in C++, but I don\'t know how to do it. I would like to do something like that (pseudocode):
map
This is indeed possible in C++, thanks to function pointers. Here's a simple example:
std::string foo() { return "Foo"; }
std::string bar() { return "Bar"; }
int main()
{
std::map<std::string, std::string (*)()> m;
// Map the functions to the names
m["foo"] = &foo;
m["bar"] = &bar;
// Display all of the mapped functions
std::map<std::string, std::string (*)()>::const_iterator it = m.begin();
std::map<std::string, std::string (*)()>::const_iterator end = m.end();
while ( it != end ) {
std::cout<< it->first <<"\t\""
<< (it->second)() <<"\"\n";
++it;
}
}
This gets more tricky when dealing with functions with different return types and arguments. Also, if you are including non-static member functions, you should use Boost.Function
.