Implementing the visitor pattern using C++ Templates
问题 I've been trying to reduce the amount of boilerplate in my code, by using C++ Templates to implement the visitor pattern. So far I've come up with this: class BaseVisitor { public: virtual ~BaseVisitor() {} }; template<typename T> class Visitor : public BaseVisitor { public: virtual void visit(T& /* visitable */) = 0; }; template<typename Derived> class Visitable { public: void accept(Visitor<Derived>& visitor) { visitor.visit(static_cast<Derived&>(*this)); } }; And each subclass of Visitable