I’m not sure if this is possible in C++. I know you can pass a pointer to a function or static member function as a parameter. I want a function pointer for a specific object, so that when the function is executed, it is done on the object.
class MyClass
{
public:
MyClass(int id){mId = id;}
void execute(){cout<<mId<<endl;}
private:
int mId;
};
MyClass obj1(1);
MyClass obj2(2);
typedef (Executor)();
Executor ex1 = &obj1::execute();
Executor ex2 = &obj2::execute();
So when ex1 is executed, “1” should be printed and if ex2 is execute, “2” is printed. Is this possible?
The facility that handles this is the function template
bind:You can store a bind in a
functionobject:Note that by default
bindwill storeobjby value; you can store a reference withref:A related facility is
mem_fn, which wraps a member function pointer:However, because
mem_fndoesn’t bind an instance, you have to supply the instance each time you call it.In order to avoid writing the class name when binding a member function, you can use a macro:
A macro is necessary because you can only form a member function pointer from its type and name, and you cannot pass a name (an unqualified-id) to a function.