For example, in the following pseudo code, Class B need to call A::Action() through B::m_cb member.
The objective is, how to make a general, non-template Callback class, so "B" does not have to be a template, and the "CallBack" can hold any kind of function signature.
I ever use such code before, but now I can not find that implementation. All I remember is:
- the "CallBack" itself is not a template, but it contains member template
- the helper function template make_callback will instantiate CallBack object
Can anyone give a poiinter?
Class A
{
public:
void Action(){//...};
};
class CallBack
{
//...
// CallBack it self it is a NOT a template
// It can wrap member template though
};
class B
{
public:
void SetCallback(CallBack to){
m_cb = to;
}
void do_something()
{
//...
m_cb.Execute();
//...
}
private:
CallBack m_cb;
};
int main()
{
A obj1;
CallBack cb = make_callback(&obj1, &A::Action);
B obj2;
obj2.SetCallback(cb);
//....
obj2.do_something();
}
Here is the sample code I got from this same website. I tried to improved it a little bit, so it can tolerate arbitrary call back function's return type. But it still can not handle arbitrary number of arguments, like in line 18. Also, , T is the pointer to member function, which should be depend on C. I don't know how to enforce this.
#include <iostream>
#include <memory>
// INTERNAL CLASSES
class CallbackSpecBase
{
public:
virtual ~CallbackSpecBase() {}
virtual void operator()(...) const = 0;
};
template<class C, class T>
class CallbackSpec : public CallbackSpecBase
{
public:
CallbackSpec(C& o, T m) : obj(o), method(m) {}
/*line 18*/ void operator()(...) const { (&obj->*method)(); } // how to pass "..." into method(...)
private:
C& obj;
T method;
};
// PUBLIC API
class Callback
{
public:
Callback() {}
void operator()() { (*spec)(); }
template<class C, class T>
void set(C& o, T m) { spec.reset(new CallbackSpec<C, T>(o, m)); }
private:
std::auto_ptr<CallbackSpecBase> spec;
};
// TEST CODE
class Test
{
public:
void foo() { std::cout << "Working" << std::endl; }
void bar() { std::cout << "Like a charm" << std::endl; }
};
int main()
{
Test t;
Callback c;
c.set(t, &Test::foo);
c();
c.set(t, &Test::bar);
c();
}