0

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.

Community
  • 1
  • 1
10rotator01
  • 635
  • 6
  • 15
  • 1
    `Delegate` is a class template so its template argument needs to be provided. The template argument in this case should be the class name. Since you want this to be optional you should go with a `std::function` instead of writing your own. – David G Jan 10 '15 at 01:47
  • I don't want to write my own delegate for the sake of writing it myself but this is an assignment I was given at university. Thank you for providing std::function though. I might be able to use its implementation to solve my problem. – 10rotator01 Jan 10 '15 at 01:56
  • 2
    The key technique for this is called **type erasure**. That's what `std::function` is all about. Look it up. Additionally you'll have to implement argument forwarding for C++03. – Cheers and hth. - Alf Jan 10 '15 at 02:29

0 Answers0