There are three approaches here.
The first is - you need to do double dispatch. You have one visitor for one side and one visitor for the other side. Once you pick one side, you "save" that type as a template parameter, which you can use to visit the other side:
template <typename T>
struct Right : Visitor {
Right(T const* lhs) : lhs(lhs) { }
T const* lhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
void visit_impl(T const& x) { result = equalNode(*lhs, x); }
template <typename U> void visit_impl(U const&) { result = false; }
};
struct Left : Visitor {
Left(Base const* lhs, Base const* rhs) : rhs(rhs) {
lhs->accept(*this);
}
Base const* rhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
template <typename U>
void visit_impl(U const& lhs) {
Right<U> right(&lhs);
rhs->accept(right);
result = right.result;
}
};
bool equalTree(const Base *lhs, const Base *rhs) {
return Left(lhs, rhs).result;
}
The second is - you cheat. You only care about the cases where the two sides are the same type, so you only need single dispatch:
struct Eq : Vistor {
Eq(Base const* lhs, Base const* rhs) : rhs(rhs) {
lhs->accept(*this);
}
Base const* rhs;
bool result;
void visit(A const& x) override { visit_impl(x); }
void visit(B const& x) override { visit_impl(x); }
void visit(C const& x) override { visit_impl(x); }
template <typename U>
void visit_impl(U const& x) {
result = equalNode(x, *static_cast<U const*>(rhs));
}
};
bool equalTree(Base const* lhs, Base const* rhs) {
if (typeid(*lhs) == typeid(*rhs)) {
return Eq(lhs, rhs).result;
} else {
return false;
}
}
The third is - you don't do this through OO and instead use a variant
:
using Element = std::variant<A, B, C>;
struct Eq {
template <typename T>
bool operator()(T const& lhs, T const& rhs) const {
return equalNode(lhs, rhs);
}
template <typename T, typename U>
bool operator()(T const&, U const&) const {
return false;
}
};
bool equalTree(Element const& lhs, Element const& rhs) {
return std::visit(Eq{}, lhs, rhs);
}