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 (
I'm assuming an interface like this:
void Timer::register_callback( void(*callback)(void*user_data), void* user_data );
template
void wrap_method_callback( void* class_pointer )
{
AnyClass*const self = reinterpret_cast(class_pointer);
(self->*Func_Value)();
}
class A
{
public:
void callback()
{ std::cout << m_i << std::endl; }
int m_i;
};
int main ()
{
Timer t;
A a = { 10 };
t.register_callback( &wrap_method_callback, &a );
}
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 only AnyClass*
pointers are passes as void*
to the callback registration.