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 (*)(void), when the Elapsed event happens the function pointer is called.
Is possible to do the same thing with a member function that has also the signature void (AnyClass::*)(void)?
Thanks mates.
EDIT: This code has to work on Windows and also on a real-time OS (VxWorks) so not using external libraries would be great.
EDIT2: Just to be sure, what I need is to have a Timer class that take an argument at the Constructor of tipe "AnyClass.AnyMethod" without arguments and returning void. I have to store this argument and latter in a point of the code just execute the method pointed by this variable. Hope is clear.
Maybe the standard mem_fun is already good enough for what you want. It's part of STL.
boost::function looks like a perfect fit here.
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:
Now you can just use Callback as a callback storing mechanism so:
And
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.
I'm assuming an interface like this:
I think a better solution would be to upgrade call you callback to either use boost::function or a homegrown version (like Kornel's answer). However this require real C++ developers to get involved, otherwise you are very likely to introduce bugs.
The advantage of my solution is that it is just one template function. Not a whole lot can go wrong. One disadvantage of my solution is it may slice your class with cast to
void*
and back. Be careful that onlyAnyClass*
pointers are passes asvoid*
to the callback registration.