I am using the visitor pattern to traverse a tree made up of many different types of nodes, something like this:
class Visitor
{
public:
virtual void visit(TypeA &) = 0;
virtual void visit(TypeB &) = 0;
virtual void visit(TypeC &) = 0;
virtual void visit(TypeD &) = 0;
virtual void visit(TypeE &) = 0;
virtual void visit(TypeF &) = 0;
virtual void visit(TypeG &) = 0;
virtual void visit(TypeH &) = 0;
virtual void visit(Returner &) = 0;
virtual void visit(Caller &) = 0;
};
Each of the visitor functions can potentially call any other visitor function since the Types are arranged in a tree. For example, visit(TypeA &) might be implemented as follows:
void ClassWhichInheritedVisitor::visit(TypeA & a){
a.bChild->accept(*this);
a.fChild->accept(*this);
a.callerChild->accept(*this);
}
Now, I have a value generated in visit(Returner &) which I would like to pass back to the most recent call of visit(Caller &). My current solution is to throw the value from visit(Returner &) and catch it in visit(Caller &), however, I have read that exception handling can be very slow.
One solution might be to store the return value in some member variable and check for a value after each call to accept(*this) for any child, however, this makes the code bloated and difficult to read. Maybe this could be eased with a preprocessor macro?
#define visit(target); \
target->accept(*this); \
if (returnValuePresent) \
return;
Is there a more idiomatic way to return this value without checking for a value after each call to accept(*this), considering that there might easily be 5/6 function calls between the call to visit(Caller &) and visit(Returner &)?