© Dmitri Nesteruk 2022
D. NesterukDesign Patterns in Modern C++20https://doi.org/10.1007/978-1-4842-7295-4_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, for example:
(1.0 + (2.0 + 3.0))
This expression can be presented as a hierarchy similar to the following:
struct Expression
{
  // nothing here (yet)
};
struct DoubleExpression ...

Get Design Patterns in Modern C++20: 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.