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 (
The best solution I have used for that same purpose was boost::signal or boost::function libraries (depending on whether you want a single callback or many of them), and boost::bind to actually register the callbacks.
class X {
public:
void callback() {}
void with_parameter( std::string const & x ) {}
};
int main()
{
X x1, x2;
boost::function< void () > callback1;
callback1 = boost::bind( &X::callback, &x1 );
callback1(); // will call x1.callback()
boost::signal< void () > multiple_callbacks;
multiple_callbacks.connect( boost::bind( &X::callback, &x1 ) );
multiple_callbacks.connect( boost::bind( &X::callback, &x2 ) );
// even inject parameters:
multiple_callbacks.connect( boost::bind( &X::with_parameter, &x1, "Hi" ) );
multiple_callbacks(); // will call x1.callback(), x2.callback and x1.with_parameter("Hi") in turn
}