Suppose I have some code like this:
class Visitor { public: Visitor(callBackFunction) {} void visit() { //do something useful invokeCallback(); } } class ClassThatCanBeVisited { Visitor &visitor; public: ClassThatCanBeVisited(Visitor &_visitor) : visitor(_visitor){} void someUsefulMethod() { int data= 42; visitor.visit(data); } }; void callBackFunction() { //do something useful in the context of the Main file } int main() { Visitor visitor; ClassThatCanBeVisited foo(visitor); foo.someUsefulMethod(); }
I need to create a simple callback that will be called whenever the Visitor::visit() is called. I know that I probably should put the code of the callback inside my Visitor, but it is in a different context, so I would like to pass the callBackFunction() to the Visitor so he could invoke my callback function.
I looked for things on the web and saw boost::function, but c++ already has the basic functors.
Which one should I use for better clarity of the code? The callback is going to be a simple void() function, but it might grow, you never know the future 🙂
What is the recommended way to do this?
You can use callback interface and its hierarchy if you don’t want to use boost::function.
If you have or can use boost::function – use it, it is a good way to get rid of all those callback classes.
Edit:
@edisongustavo:
boost::function and boost::bind won’t probably make your code more readable. But it will give you an opportunity to pass free functions ( I mean functions out of class and static class functions ) as callback as well as existing functions of any class.
With boost functions you can pass functions with for example 2 parameters as callback which expect only one parameter.
But again, this won’t make your code more readable unless all your team knows and favor boost.