Inserting into a map of member function pointers

c++

Solution

First, the code:

#include <map>
#include <string>
class a
{
public:
     a()
     {
       pointerMap["func1"] = &a::func1;
       pointerMap["func2"] = &a::func2;
     }

     void invoke(const std::string& name, int x, int y) {
       if(pointerMap[name])
         (this->*pointerMap[name])(x, y);
     }

private:
     void func1(int a, int b) {};
     void func2(int a, int b) {};
     std::map<std::string, void (a::*)(int, int)> pointerMap;
};

int main () {
  a o;
  o.invoke("func1", 1, 2);
}

Now, for your questions:

my question is, is this the right way to go about adding pointers to member functions to a map within an object

I find the subscript operator `[]` much easier to read than the insert that you were doing.

so that you are only referencing the individual instance's func1 or func2.

Pointer-to-member-function doesn't have an instance associated with it. You bind the pointer to an instance when you invoke it. So, your map could have been a static member just as easily.

how i would go about calling this function from the pointer.

The syntax is either: `(instance.*pointer)(args)` or `(class_pointer->*pointer)(args)`. Since you didn't say what instance the functions should be invoked on, I assumed `this`. Your pointers live in the map, so we have:

((this)->*(this->pointerMap["func1"]))(arg1, arg2)

or

(this->*pointerMap[name])(x, y);

Problem

My question is a little complicated so I'll start with an example: ``` class a { public: a() { pointerMap.insert(pair<std::string, void a::*(int, int)> ("func1", func1); pointerMap.insert(pair<std::string, void a::*(int, int)> ("func2", func2); } private: void func1(int a, int b); void func2(int a, int b); std::map<std::string, void a::* (int, int)> pointerMap; } ``` My question is, is this the right way to go about adding pointers to member functions to a map within an object, so that you are only referencing the individual instance's `func1` or `func2`? And also, I have no clue how I would go about calling this function from the pointer. Would it be something like this? ``` map["func1"](2,4); ``` I'm a little confused about the syntax when working with member functions.

Original source