I need a table that maps codes to C++ member functions. Suppose we have this class:
class foo
{
bool one() const;
bool two() const;
bool call(char*) const;
};
What I want is a table like this:
{
{ “somestring”, one },
{ ”otherstring”, two }
};
So that if I have a foo object f, f.call(”somestring”) would look up “somestring” in the table, call the one() member function, and return the result.
All of the called functions have identical prototypes, i.e., they are const, take no parameters, and return bool.
Is this possible? How?
Since you only need to store members of the same class, with the same arguments and return types, you can use pointer-to-member-functions:
That uses the new initialisation syntax of C++11. If your compiler doesn’t support it, there are various other options. You could initialise the map with a static function:
or you could use Boost.Assignment:
or you could use an array, and find the entry with
std::find_if(or a simpleforloop if your library doesn’t have that yet), orstd::binary_searchif you make sure the array is sorted.