c++ callbacks to member functions of any generic object
Posted on 2007-10-13
I would like to implments a c++ callback like this:
//instantiate various user-defined objects:
// subscribe the objects to me's Notify() function, so that when me.Notify() is called, each subscribing objcect has its own OnNotify() called;
me.subscribe( jack.OnNotify() )
me.subscribe( dianne.OnNotify() )
me.subscribe( pooch.OnNotify() )
Person::OnNotify() will be defined differently than Dog::OnNotify(), but will have the same signature.
It is critical that I subscribe member functions to the callback rather than static functions.
Person::subscribe( function_pointer ) will insert the function pointer into a vector of function pointers.
Person::Notify() will iterate over the vector of function pointers, calling (*iter)() for each one.
I understand that this is rather difficult to do in c++ and that there are issues regarding type-safety, doing it with different types (Dog and Person), and needing to use member functions.
I have found examples online (and even on EE) that deal with these issues and use templates, passing of a pointer to the instance, templates, functors, etc. But the examples were not explained clearly or slightly different than what I need to do above.
I'm a little overwhelmed and was hoping one of y'all had crossed this bridge before and found a simple, correct solution.
Thanks a ton guys,