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.
First, the code:
Now, for your questions:
I find the subscript operator
[]much easier to read than the insert that you were doing.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.
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 assumedthis. Your pointers live in the map, so we have:or