Questions about workarounds for templated functions that must be virtual are quite common here, though I couldn't find anything that helps with my problem, which is a simple variation of this question: need a virtual template member workaround
The proposed approach is using type erasure leading to a very clean and simple solution. However, what if I need to return a value from the visit()
method? The OP already had this aspect in his question, but since he never used the result it was ignored in the solution.
Now imagine this code instead:
template <typename T>
class BaseVisitor {
public:
BaseVisitor();
T visit(BaseVisited *visited);
virtual ~BaseVisitor();
}
class BaseVisited {
BaseVisited();
template <typename T>
virtual T accept(BaseVisitor<T> *visitor) { return visitor->visit(this); };
virtual ~BaseVisited();
}
We still need accept()
to be templated, even after applying the type erasure trick. Any further ideas?
Note: I cannot use a base class for the return value, as has been suggested in some of the answers on SO, because T can stand for any base type as well (int, string etc.).