How to create map<string, class::method> in c++ and be able to search for function and call it?

user360872 picture user360872 · Jun 24, 2010 · Viewed 23.4k times · Source

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<string, method> mapping =
{
  "sin", Math::sinFunc,
  "cos", Math::cosFunc,
  ...
};

...

string &function;
handler = mapping.find(function);
int result;

if (handler != NULL)
  result = (int) handler(20);

To be honest I don't know is it possible in C++. I would like to have a map of string, method and be able to search for function in my mapping. If given string name of function exists then I would like to call it with given param.

Answer

Dummy00001 picture Dummy00001 · Jun 25, 2010

Well, I'm not a member of the popular here Boost Lovers Club, so here it goes - in raw C++.

#include <map>
#include <string>

struct Math
{
    double sinFunc(double x) { return 0.33; };
    double cosFunc(double x) { return 0.66; };
};

typedef double (Math::*math_method_t)(double);
typedef std::map<std::string, math_method_t> math_func_map_t;

int main()
{

    math_func_map_t mapping;
    mapping["sin"] = &Math::sinFunc;
    mapping["cos"] = &Math::cosFunc;

    std::string function = std::string("sin");
    math_func_map_t::iterator x = mapping.find(function);
    int result = 0;

    if (x != mapping.end()) {
        Math m;
        result = (m.*(x->second))(20);
    }
}

That's obviously if I have understood correctly that you want a method pointer, not a function/static method pointer.