I have created a Timer class that must call a callback method when the timer has expired. Currently I have it working with normal function pointers (they are declared as void (
Dependencies, dependencies... yeah, sure boost is nice, so is mem_fn, but you don't need them. However, the syntax of calling member functions is evil, so a little template magic helps:
class Callback
{
public:
void operator()() { call(); };
virtual void call() = 0;
};
class BasicCallback : public Callback
{
// pointer to member function
void (*function)(void);
public:
BasicCallback(void(*_function)(void))
: function( _function ) { };
virtual void call()
{
(*function)();
};
};
template
class ClassCallback : public Callback
{
// pointer to member function
void (AnyClass::*function)(void);
// pointer to object
AnyClass* object;
public:
ClassCallback(AnyClass* _object, void(AnyClass::*_function)(void))
: object( _object ), function( _function ) { };
virtual void call()
{
(*object.*function)();
};
};
Now you can just use Callback as a callback storing mechanism so:
void set_callback( Callback* callback );
set_callback( new ClassCallback( my_class, &MyClass::timer ) );
And
Callback* callback = new ClassCallback( my_class, &MyClass::timer ) );
(*callback)();
// or...
callback->call();