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?