Visitors in modern C++
As we have just seen, the Visitor pattern promotes the separation of concerns; for example, the order of serialization and the mechanism of serialization are made independent, and a separate class is responsible for each. The pattern also simplifies code maintenance by collecting all code that performs a given task in one place. What the Visitor pattern does not promote is code reuse with no duplication. But that’s the object-oriented Visitor pattern, before modern C++. Let’s see what we can do with the generic capabilities of C++, starting from the regular Visitor pattern.
Generic Visitor
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...