I have a Class A which I intend to put in a shared library as it interacts with the device drivers.
I have a Class B and may be C,D,E… in future which will use the class A using the shared library.
I want a capability of setting a callback function in Class A so that when a specific event occurs a non-static members function of class B,C,D,E … should be called by Class A.
I searched on google for callback function in C++ but found that non-static member functions are not supported by C-style definition of callbacks.
Can it be done using function pointers ?
Kindly give some suggestions for callbacks in C++ which do not violate the OOPS concepts.
I also came around a library called ‘Boost’ which offers similar functionality but I want to avoid the overhead of the extra library if possible. Is Boost recommended for callback function ?
EDIT : The B,C,D,E will not share any hierarchy and they will be completely independent classes. But all of them would have object of class A. And class A would also have a public function to set the callback function.
One option, if you really really want to avoid the nearly unimportant overhead of a polymorphic function wrapper, is to make those functions static and have them take a “user data”
void*parameter, pointing to an appropriate instance of the class the function is a member of. Inside the static function, you then cast back to the appropriate type:Live example on Ideone.
I personally would recommend using
std::function, though, since the above is severly limited in what can be accepted as a callback.std::functionis a polymorphic function wrapper, meaning that it can take normal function pointers, member function pointers and even functors (function objects) and invoke them all in the same manner. Together withstd::bind, which allows you to bind parameters to a function, you can make easy callbacks to member functions. Boost offers them too (Boost.Function, Boost.Bind).Live example on Ideone.
Basically
std::binddoes automatically what you had to do manually in the first version, it saves the object pointer and invokes the member function on it. It doesn’t do this through avoid*pointer, however, and insteadstd::bindreturns a different binder type for every different object pointer. That’s why you needstd::function, since it doesn’t care what you pass it.