© Dmitri Nesteruk 2018
Dmitri NesterukDesign Patterns in Modern C++https://doi.org/10.1007/978-1-4842-3603-1_24

24. Visitor

Dmitri Nesteruk1 
(1)
St. Petersburg, Russia
 

Once you’ve got a hierarchy of types, unless you have access to the source code, it is impossible to add a function to each member of the hierarchy. This is a problem that requires some advance planning, and gives birth to the Visitor pattern.

Here’s a simple example: suppose you have parsed a mathematical expression (with the use of the Interpreter pattern, of course!) composed of double values and addition operators:

1   (1.0 + (2.0 + 3.0))

This expression can be presented as a hierarchy similar to the following:

 1   struct Expression
 2   {
 3     // nothing here (yet)
 4   };
 5

Get Design Patterns in Modern C++: Reusable Approaches for Object-Oriented Software Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.