Hi there,
I'm trying to write a simple Delegate class with a Bind() and Invoke() function. For now it only needs to support a void class function with no parameters. I've searched around and found quite a few exmaples, though, those class are heavily templated and I lose track trying to simplify it.
So far my code is following:
The part I am having difficulty with is assigning &Test::DoSomething to the m_Callback variable.Code:#include <windows.h>
class Test
{
public:
void DoSomething()
{
MessageBox(NULL, L"Test::DoSomething!", NULL, 0);
}
};
template<class tObject, void (tObject::*Func)()>
void Wrapper(void* Object)
{
return ((tObject *)(Object)->*Func)();
}
class Delegate
{
public:
typedef void (*FuncType)(void *);
template <class tObject>
void Bind(tObject *Object, void (tObject::*Callback)())
{
m_Object = Object;
m_Callback = &Wrapper<tObject, &tObject::DoSomething>; // Works, but need to replace DoSomething with Callback variable somehow
// ((tObject *)m_Object->*Callback)(); // This works, but needs to be in Invoke function, so these variables need saving somehow
};
void Invoke()
{
(*m_Callback)(m_Object); // Works if m_Callback is saved with Wrapper helper class
};
private:
void *m_Object;
FuncType m_Callback;
};
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
Test test;
Delegate dg;
dg.Bind(&test, &Test::DoSomething);
dg.Invoke(); // Call test.DoSomething();
return 0;
};
&tObject::DoSomething works, yet _Callback which I pass &Test::DoSomething to does not work.
Where am I going wrong?
Thanks.
[EDIT] Also, why does the following line work:
When wrapper is like:Code:m_Callback = &Wrapper<tObject, &tObject::DoSomething>;
Should it not be Wrapper<class-typename, parameter-1>(parameter-2) // This currently creates an errorCode:template<class tObject, void (tObject::*Func)()>
void Wrapper(void* Object)