January 2019
Intermediate to advanced
512 pages
14h 5m
English
We are going to try to reduce the boilerplate code in the implementation of the Visitor pattern. Let's start with the accept() member function, which must be copied into every visitable class; it always looks the same:
class Cat : public Pet { void accept(PetVisitor& v) override { v.visit(this); }};
This function cannot be moved to the base class because we need to call the visitor with the actual type, not the base type—visit() accepts Cat*, Dog*, and so on; not Pet*. We can get a template to generate this function for us if we introduce an intermediate templated base class:
class Pet { // Same as before public: virtual ~Pet() {} Pet(const std::string& color) : color_(color) {} const std::string& color() const { return color_; ...