Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

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 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_; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content