I have to write a delegate in C++ (no C++11 features are allowed) that basically has the two methods Bind()
and Invoke()
. It should be possible to bind free functions, member functions of any class and const member functions of any class. Bind()
stores the function pointer and Invoke()
calls the function pointer that was last bound.
I was given example code, which should compile the way given:
void Function(float, double);
Delegate d;
d.Bind(&Function);
d.Invoke(1.0, 10);
As far this is not a problem.
class Temp
{
public:
void DoSomething(float, double);
};
Delegate d;
Temp t;
d.Bind(&Temp::DoSomething, &t);
d.Invoke(2.0, 20);
Now here is my problem. I wanted to solve this with templates and I am pretty sure that is the way to go. So then I would define something like this:
template<class T>
class Delegate
{
public:
//here are all the overloads, that is not the difficulty
private:
void (*FunctionPointer)(int, float);
void (T::*memberFunctionPointer)(int, float); //this is my problem
}
But if I define my class this way I cannot instantiate a delegate by just writing
Delegate d;
I first receive the type for the memberFunctionPointer
, when Bind()
is called on delegate.
So, is there a way to do this?
I have already looked at this post https://stackoverflow.com/a/9568485/3827069 but I was not able to come up with a solution by myself.