Visitor
What you will learn on this page
Section titled “What you will learn on this page”- What the Visitor pattern is for: adding operations to a set of classes that rarely changes, without editing those classes each time.
- How double dispatch picks the right code from two types at once: the kind of node, and the kind of operation.
- The trade-off at its heart: new operations become easy, and new kinds of node become harder, but the compiler tells you every place that needs a change.
- The modern C++ alternative,
std::variantwithstd::visit, and when to prefer it.
The problem
Section titled “The problem”A calculator, a spreadsheet, or a pricing engine holds formulas as
trees: numbers, variables, +, *, and unary minus. The kinds of node
change rarely; what changes is what the program does with a tree.
- FR-1 Evaluate a formula, given values for its variables.
- FR-2 Show a formula as text, with explicit grouping.
- FR-3 List the variables a formula uses, so that a form can ask for their values.
- FR-4 More operations will follow: simplifying, checking units, turning a formula into code. Each should be written in one place, without changing the node classes.
- FR-5 When a new kind of node is added, every operation must handle it, and forgetting one must not go unnoticed.
The straightforward solution
Section titled “The straightforward solution”The node classes are kept as plain data. Each operation is a free
function, which asks the node which kind it is with dynamic_cast:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace before {
// The base of every node in an expression tree such as `(x + 2) * -y`. It// has no operations of its own: in this first design, each operation is a// free function that asks a node which kind it is.class Expr {public: // Virtual, so deleting a node through an Expr pointer runs the right // destructor, which in turn frees that node's children. dynamic_cast // also needs the class to have at least one virtual function. virtual ~Expr() = default; // `= delete`: nodes cannot be copied. A tree is owned through // unique_ptrs, and a copy would have to decide what to do with them. Expr(const Expr&) = delete; Expr& operator=(const Expr&) = delete;
protected: // Only derived classes (the node kinds) can construct an Expr. Expr() = default;};
// An owning pointer to a node that cannot be changed (`const Expr`). Each// parent owns its children through these, so destroying the root frees the// whole tree.using ExprPtr = std::unique_ptr<const Expr>;
// A literal number, such as 2.class Number final : public Expr {public: explicit Number(double value) : value_{value} {} double value() const { return value_; }
private: double value_;};
// A named variable, such as `x`; its value is looked up when evaluating.class Variable final : public Expr {public: // Takes the name by value and moves it into the member: one copy at most. explicit Variable(std::string name) : name_{std::move(name)} {} const std::string& name() const { return name_; }
private: std::string name_;};
// left + right. Takes ownership of both children: std::move hands each// unique_ptr over, and the caller's pointers are left empty.class Add final : public Expr {public: Add(ExprPtr left, ExprPtr right) : left_{std::move(left)}, right_{std::move(right)} {} // *left_ follows the pointer to the child node itself. Returns a // reference, so nothing is copied; it is valid while this Add lives. const Expr& left() const { return *left_; } const Expr& right() const { return *right_; }
private: ExprPtr left_, right_;};
// left * right, owned the same way as Add.class Multiply final : public Expr {public: Multiply(ExprPtr left, ExprPtr right) : left_{std::move(left)}, right_{std::move(right)} {} const Expr& left() const { return *left_; } const Expr& right() const { return *right_; }
private: ExprPtr left_, right_;};
// -operand. Added to the program after evaluate and variables were written.class Negate final : public Expr { // added laterpublic: explicit Negate(ExprPtr operand) : operand_{std::move(operand)} {} const Expr& operand() const { return *operand_; }
private: ExprPtr operand_;};
// Each operation asks "which kind of node is this?" with dynamic_cast.// When Negate was added, someone had to find and update every such// function by hand. One was updated and one was missed, and the compiler// could not warn about it: nothing links the list of node kinds to the list// of cases in each function.// evaluate: the value of the expression, using `values` for the// variables. Throws std::out_of_range if a variable has no value.double evaluate(const Expr& e, const Variables& values); // updated for Negate// variables: the names of the variables the expression uses, sorted.Names variables(const Expr& e); // not updatedVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Collects the names of the variables in the tree under `e`, by asking// "is it this kind? is it that kind?" and calling itself on the children.// This is the function that was never updated for Negate.Names variables(const Expr& e) { Names names; // `dynamic_cast<const Variable*>(&e)` checks, while the program runs, // whether `e` really is a Variable. If it is, the result points to it // as a Variable; if not, the result is nullptr. Declaring `v` inside // the `if` tests that pointer: the branch runs only for a Variable. if (const auto* v = dynamic_cast<const Variable*>(&e)) { names.insert(v->name()); } else if (const auto* a = dynamic_cast<const Add*>(&e)) { // Call variables on each child, then merge moves the names from // that returned set into `names`. A name already present is not // added twice: a std::set holds each value once. names.merge(variables(a->left())); names.merge(variables(a->right())); } else if (const auto* m = dynamic_cast<const Multiply*>(&e)) { names.merge(variables(m->left())); names.merge(variables(m->right())); } // A Number has no variables. So, by accident, has a Negate: this // function was written before Negate existed, and nothing said so. return names;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `values` (above, outside this snippet) gives `x = 3` and `y = 4`.// The braces make a scope, so `using namespace before` applies only// inside it, and the tree is destroyed at the closing brace.{ using namespace before; // (x + 2) * -y // The root, a Multiply, is a local object; every node below it is // made with std::make_unique and owned by its parent. A // std::unique_ptr<Add> converts to the ExprPtr the constructor // takes. Number(2) receives the int 2 as the double 2.0. const Multiply tree{ std::make_unique<Add>(std::make_unique<Variable>("x"), std::make_unique<Number>(2)), std::make_unique<Negate>(std::make_unique<Variable>("y"))}; // join (top of this file) puts the names in one string with spaces. // evaluate knows about Negate and gives -20; variables does not, // so it never looks inside `-y` and reports only `x`. std::cout << "before: value " << evaluate(tree, values) << ", variables " << join(variables(tree)) << '\n';}The first line of the output, under Check, shows the problem:
the formula (x + 2) * -y has two variables, and variables finds
only x.
- This design does meet FR-4. A new operation is one new function, and the node classes do not change. That is worth keeping.
- It fails FR-5, silently.
Negatewas added aftervariableswas written.evaluatewas updated andvariableswas not, and nothing said so: an unknown node falls through theifchain and is treated like a number. The compiler cannot help, because nothing in the code says which kinds of node exist. - Each call tries the kinds in turn. A
dynamic_castper kind, per node visited. With five kinds that is cheap; it grows with the list.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) fails// unless the two are equal. They come from the site's small test header,// lld_test.hpp.// This test pins the bug, so that fixing it would be noticed: the tree// `-y` uses the variable `y`, yet variables() returns an empty set. The// {{"y", 4.0}} argument builds a Variables map with one entry, `y = 4`.LLD_TEST(before_a_new_node_type_is_silently_skipped) { using namespace before; const Negate tree{std::make_unique<Variable>("y")}; LLD_CHECK_EQ(before::evaluate(tree, {{"y", 4.0}}), -4.0); // updated LLD_CHECK(before::variables(tree).empty()); // not updated: wrong}The other obvious design, a virtual function per operation in every node class (as on the Interpreter page), fails the other way: FR-5 is checked by the compiler, but every new operation changes every node class (FR-4).
The pattern
Section titled “The pattern”Visitor puts each
operation on a set of classes into a class of its own, a visitor,
with one function per kind of element. Each element has a single
accept function, which calls the visitor’s function for its own
kind.
Its participants:
- The visitor interface: one
visitfunction per kind of element. Here,Visitor, with five. - Concrete visitors: one per operation. Here,
Evaluator,Printer, andVariableCollector. - The element interface: one function,
accept, that takes any visitor. Here,Expr. - Concrete elements: the node classes. Each implements
acceptby callingvisitor.visit(*this). - The object structure: the tree, which the visitors walk.
The list of kinds is written once, in the visitor interface. That list is what gives FR-5 its check: a visitor that does not handle every kind is an abstract class and cannot be created.
Text description of the diagram
A class diagram in two halves. On one side, the abstract class Visitor has five functions, one visit for each kind of node: Number, Variable, Add, Multiply, and Negate. Three classes derive from it, one per operation: Evaluator, Printer, and VariableCollector. On the other side, the abstract class Expr has one function, accept, which takes a visitor. Five node classes derive from it: Number holds a value; Variable holds a name; Add and Multiply each hold a left and a right operand; and Negate holds one operand. A dashed arrow from Expr to Visitor shows that accept calls a visit function. Adding an operation adds one class on the Visitor side; adding a kind of node adds one class on the Expr side and one function to Visitor and to every class derived from it.
Diagram source (Mermaid)
classDiagram
class Visitor {
<<abstract>>
+visit(Number) void
+visit(Variable) void
+visit(Add) void
+visit(Multiply) void
+visit(Negate) void
}
class Evaluator
class Printer
class VariableCollector
class Expr {
<<abstract>>
+accept(visitor) void
}
class Number {
-double value_
}
class Variable {
-string name_
}
class Add {
-ExprPtr left_
-ExprPtr right_
}
class Multiply {
-ExprPtr left_
-ExprPtr right_
}
class Negate {
-ExprPtr operand_
}
Visitor <|-- Evaluator
Visitor <|-- Printer
Visitor <|-- VariableCollector
Expr <|-- Number
Expr <|-- Variable
Expr <|-- Add
Expr <|-- Multiply
Expr <|-- Negate
Expr ..> Visitor : accept calls visitThe classic C++ implementation
Section titled “The classic C++ implementation”The two interfaces
Section titled “The two interfaces”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Forward declarations: "these classes exist and are defined later". That// is enough for Visitor to take them by reference below, before the node// classes themselves are written.class Number;class Variable;class Add;class Multiply;class Negate;
// One visit function per kind of node. An operation on the tree is a// class that derives from Visitor.// All five functions are called visit; the compiler picks one by the type// of the argument. Each is pure virtual (`= 0`), so an operation that// leaves one out is still abstract and cannot be created: adding a sixth// kind of node here makes every operation fail to compile until it handles// the new kind.class Visitor {public: virtual ~Visitor() = default; virtual void visit(const Number& node) = 0; virtual void visit(const Variable& node) = 0; virtual void visit(const Add& node) = 0; virtual void visit(const Multiply& node) = 0; virtual void visit(const Negate& node) = 0;
protected: // Protected so that only derived visitors can be built or copied, and // copying through a Visitor& (which would copy only the base part) does // not compile. Visitor() = default; Visitor(const Visitor&) = default; Visitor& operator=(const Visitor&) = default;};
// The base of every node. Nodes cannot be copied (`= delete`); a tree is// owned through unique_ptrs, parent to child.class Expr {public: virtual ~Expr() = default; Expr(const Expr&) = delete; Expr& operator=(const Expr&) = delete;
// Calls the visit function for this node's own type. // This is the only operation a node has. The node is const (it is not // changed) but the visitor is not, because a visitor builds up its // result as it goes. virtual void accept(Visitor& visitor) const = 0;
protected: Expr() = default;};
// An owning pointer to a node that cannot be changed. Destroying the root// pointer frees the whole tree.using ExprPtr = std::unique_ptr<const Expr>;- The node classes are declared before
Visitor, but not defined, so thatvisitcan take them by reference.Visitoris the one place that lists every kind of node. visitis overloaded on the node type. All five functions have the same name; the compiler picks one by the static type of the argument.accepttakes a non-constVisitor&because visitors build their results as they go; it is itselfconstbecause visiting does not change the tree.Visitor’s copy operations are protected, soa = b, with both declared asVisitor&, does not compile; it would copy only theVisitorpart (slicing). Derived visitors can still be copied as themselves.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A literal number, such as 2.class Number final : public Expr {public: explicit Number(double value) : value_{value} {} double value() const { return value_; } // Inside Number, *this is a `const Number&`, so the compiler picks // visit(const Number&). The call is virtual on the visitor, so it runs // that operation's version: Evaluator's, Printer's, and so on. void accept(Visitor& visitor) const override { visitor.visit(*this); }
private: double value_;};
// A named variable, such as `x`.class Variable final : public Expr {public: // Throws std::invalid_argument if the name is empty. explicit Variable(std::string name); const std::string& name() const { return name_; } void accept(Visitor& visitor) const override { visitor.visit(*this); }
private: std::string name_;};
// left + right. Owns both children.class Add final : public Expr {public: // Takes ownership of both children. Throws std::invalid_argument if // either one is null, so left() and right() can always follow the pointer. Add(ExprPtr left, ExprPtr right); const Expr& left() const { return *left_; } const Expr& right() const { return *right_; } void accept(Visitor& visitor) const override { visitor.visit(*this); }
private: ExprPtr left_; ExprPtr right_;};Each accept is the same one line, visitor.visit(*this), and it
cannot be moved into the base class. Inside Number::accept, the type
of *this is const Number&, so the compiler picks
visit(const Number&). In a base-class function, *this would be a const Expr&, and there is no visit(const Expr&) to call.
Double dispatch
Section titled “Double dispatch”A virtual call chooses code by one type: the object’s. Visitor needs to choose by two: the kind of node and the kind of operation. It gets there with two calls, which is why the technique is called double dispatch:
node.accept(visitor)is a virtual call on the node, so it runs, say,Multiply::accept.- Inside it, the type of
*thisis known at compile time, so overload resolution picksvisit(const Multiply&). That call is virtual on the visitor, so at run time it runs, say,Printer::visit(const Multiply&).
Text description of the diagram
A sequence diagram with four participants: the describe function, a Negate node, a Printer, and a Variable node. describe calls accept on the Negate node, passing the printer. The Negate node calls the printer’s visit function for a Negate, passing itself. The printer appends a minus sign, then calls accept on the Negate’s operand, the Variable node, passing itself. The Variable node calls the printer’s visit function for a Variable. The printer appends “y”. The calls return in reverse order, and describe then reads the printer’s text, which is “-y”.
Diagram source (Mermaid)
sequenceDiagram
participant Client as describe()
participant N as Negate node
participant P as Printer
participant V as Variable node
Client->>N: accept(printer)
N->>P: visit(this Negate)
P->>P: append "-"
P->>V: accept(this printer)
V->>P: visit(this Variable)
P->>P: append "y"
P-->>V: return
V-->>P: return
P-->>N: return
N-->>Client: return
Client->>P: text() gives "-y"The operations
Section titled “The operations”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The operations. Each is a visitor, hidden in classic.cpp.// [[nodiscard]]: the compiler warns if a caller ignores the result.// evaluate: the value, using `values` for the variables. Throws// std::out_of_range if a variable has no value.[[nodiscard]] double evaluate(const Expr& e, const Variables& values);// describe: the formula as text, with brackets around every + and *,// for example "((x + 2) * -y)".[[nodiscard]] std::string describe(const Expr& e);// variables: the names used in the formula, each once, sorted.[[nodiscard]] Names variables(const Expr& e);The public interface is three free functions. The visitors themselves
are hidden in classic.cpp, in an unnamed namespace: callers do not
need to know that this is a Visitor.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Visitors cannot return a value from visit, so each keeps its result.// The "evaluate" operation: works out the number an expression stands for.// Input: the values of the variables, given once to the constructor.// After a node has accepted it, result() is that node's value. Throws// std::out_of_range if a variable in the tree has no value.class Evaluator final : public Visitor {public: // Keeps a reference to the caller's values, not a copy. That is safe // because an Evaluator only lives inside one call to evaluate(). explicit Evaluator(const Variables& values) : values_{values} {} double result() const { return result_; }
// One visit per kind of node; each one stores the value of that node. void visit(const Number& node) override { result_ = node.value(); } // at() looks the name up and throws std::out_of_range if it is not in // the map. (The [] operator cannot be used here: the map is const.) void visit(const Variable& node) override { result_ = values_.at(node.name()); } // of(child) evaluates a child and gives back its value, so these lines // read like the arithmetic they do. void visit(const Add& node) override { result_ = of(node.left()) + of(node.right()); } void visit(const Multiply& node) override { result_ = of(node.left()) * of(node.right()); } void visit(const Negate& node) override { result_ = -of(node.operand()); }
private: // "Evaluate this sub-tree": the child accepts this same evaluator, // which runs the right visit and leaves the child's value in result_. // Returning it straight away hands back a copy before the next call // overwrites result_. double of(const Expr& e) { e.accept(*this); return result_; }
const Variables& values_; double result_ = 0.0;};How this code works: Evaluator, step by step
evaluate makes one Evaluator and calls tree.accept(evaluator).
From then on, the same evaluator travels down the tree: each visit
that has children calls of(child), which makes the child accept the
evaluator and then reads result_. Take (x + 2) * -y with x = 3 and
y = 4 (the values in main.cpp):
| Step | Running | What it does | result_ after |
|---|---|---|---|
| 1 | visit(const Multiply&) |
needs of(left) and of(right) |
0 (not set yet) |
| 2 | visit(const Add&), left |
needs of(x) and of(2) |
0 |
| 3 | visit(const Variable&), x |
values_.at("x") |
3 |
| 4 | visit(const Number&) 2 |
the number itself | 2 |
| 5 | back in Add |
3 + 2 | 5 |
| 6 | visit(const Negate&) |
needs of(y) |
5 |
| 7 | visit(const Variable&), y |
values_.at("y") |
4 |
| 8 | back in Negate |
−4 | −4 |
| 9 | back in Multiply |
5 × −4 | −20 |
evaluate then returns evaluator.result(), which is −20.
The table runs the left side first. C++ does not promise that order for
of(a) + of(b): the compiler may run the right side first. The answer is
the same either way, because each of copies result_ into its return
value straight after its own visit, before the other call can overwrite
it. If y had no value, step 7 would throw std::out_of_range, and the
exception would pass up through every visit and out of evaluate.
visitreturnsvoid, because one interface serves every operation, and they return different things (a number, a string, a set). So each visitor keeps its result in a member, and the small helperofturns “visit, then read the result” into an expression. Inof(left) + of(right), the two calls may run in either order, and each overwritesresult_, but each returns its own copy first, so the sum is right.Evaluatorholds a reference to the values. It is safe because anEvaluatorlives only insideevaluate, below, while the caller’sVariablesexists.- The visitor walks the children itself. The nodes’
acceptdoes not visit children. That lets each operation choose the order, asPrinterdoes (left, operator, right), or skip parts.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The "which variables are used?" operation. It walks the whole tree and// adds each variable's name to one set, which keeps every name once, in// sorted order. After the walk, take() hands the set over.class VariableCollector final : public Visitor {public: // Moves the set out instead of copying it. The collector's own set is // left in a valid but unspecified state, so call take() once, at the end. Names take() { return std::move(names_); }
// A number has no variables. The parameter has no name because it is // not used, but the function must still exist: Visitor requires it. void visit(const Number&) override {} void visit(const Variable& node) override { names_.insert(node.name()); } // For a node with children, visit each child with this same collector, // so all the names end up in the one set. void visit(const Add& node) override { node.left().accept(*this); node.right().accept(*this); } void visit(const Multiply& node) override { node.left().accept(*this); node.right().accept(*this); } // Leaving this out would not compile: VariableCollector would still be // abstract. That is how this version cannot miss Negate. void visit(const Negate& node) override { node.operand().accept(*this); }
private: Names names_;};VariableCollector handles Negate (FR-3), unlike the
before-version. It did not get that by being written carefully: the program could not have compiled without it. A VariableCollector without visit(const Negate&) is abstract, so variables could not create one.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three public functions all follow the same three steps: make the// visitor on the stack, let the root node accept it (which walks the whole// tree), then read the result. The visitor is destroyed when the function// returns; the tree is only borrowed through `e` and is not changed.double evaluate(const Expr& e, const Variables& values) { Evaluator evaluator{values}; e.accept(evaluator); return evaluator.result();}
std::string describe(const Expr& e) { Printer printer; e.accept(printer); return printer.text();}
// take() moves the set out of the collector, so it is not copied.Names variables(const Expr& e) { VariableCollector collector; e.accept(collector); return collector.take();}class Visitor
abstract: one visit per kind of node
Data members
Visitor(const Visitor&) = default;protected, with operator=: no slicing
Member functions
virtual void visit(const Number& node) = 0;virtual void visit(const Variable& node) = 0;virtual void visit(const Add& node) = 0;virtual void visit(const Multiply& node) = 0;virtual void visit(const Negate& node) = 0;virtual ~Visitor() = default;
class Expr
abstract; non-copyable; owned through ExprPtr
Member functions
virtual void accept(Visitor& visitor) const = 0;virtual ~Expr() = default;
class Add final
Multiply has the same shape
Data members
ExprPtr left_;ExprPtr right_;
Member functions
Add(ExprPtr left, ExprPtr right);throws std::invalid_argument if nullconst Expr& left() const;const Expr& right() const;void accept(Visitor& visitor) const override;visitor.visit(*this)
class Evaluator final
one operation; in an unnamed namespace
Data members
const Variables& values_;borrowed for one evaluate() calldouble result_;
Member functions
explicit Evaluator(const Variables& values);double result() const;void visit(const Add& node) override;and one for each other kind
The outline leaves out Number, Variable, Negate, the other two
visitors, and the functions that build trees (number, add, and so
on).
The std::variant form
Section titled “The std::variant form”When the kinds of node are a fixed list, C++ can say so directly: a
std::variant holds exactly one of a list of types. The nodes become
plain structs, and there is no base class and no accept.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Node is only declared here and defined at the bottom, because the node// kinds below need NodePtr, and Node in turn needs the node kinds. A// std::unique_ptr may point to a type that is declared but not yet defined.struct Node;// An owning pointer to a node that cannot be changed.using NodePtr = std::unique_ptr<const Node>;
// The kinds of node are plain structs: data only, no base class, no// virtual functions, no accept. The operations live elsewhere.struct Number { double value;};struct Variable { std::string name;};// Owns its two children.struct Add { NodePtr left, right;};struct Multiply { NodePtr left, right;};struct Negate { NodePtr operand;};
// A node is exactly one of these. The set of kinds is closed: it is// written here, once.// std::variant holds one value of one of the listed types at a time, and// remembers which. So a Node holds a Number, or a Variable, or an Add, and// so on. Adding a kind means adding it to this list, and then every// std::visit that does not handle it stops compiling.struct Node { std::variant<Number, Variable, Add, Multiply, Negate> kind;};- A node cannot contain itself by value, so
Addstill holds its children throughstd::unique_ptr, andNodeis declared first so thatNodePtrcan name it.Nodeis a struct around the variant, not ausingalias, because an alias cannot be declared before it is defined. The variant removes the class hierarchy, not the ownership question. - The list of kinds is in one place, the variant’s template
arguments, just as it was in
Visitor.
An operation is a call to std::visit with a callable that accepts
every type in the variant. The usual way to write one is a set of
lambdas, combined into one object:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Combines several lambdas into one object with an overloaded operator().// `class... Fs` is a template parameter pack: any number of types, here// the types of the lambdas passed in. Each lambda has its own unnamed// type with one operator(), the code that runs when it is called.// `: Fs...` makes overloaded inherit from every one of those types.template <class... Fs>struct overloaded : Fs... { // Brings every base's operator() into this struct, so they form one // overload set: calling the object with a Number picks the lambda // that takes a Number, and so on. using Fs::operator()...;};// A deduction guide: when you write overloaded{lambda1, lambda2, ...}, the// compiler works out Fs from the lambdas, since nobody can name their types.template <class... Fs>overloaded(Fs...) -> overloaded<Fs...>;overloaded derives from every lambda type it is given, and using Fs::operator()... brings all their call operators into one overload
set, so std::visit can pick the one for the type the variant holds.
The second line, a deduction guide, lets you write overloaded{...}
without naming the lambda types.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The value of the expression under `n`. Same result as classic::evaluate,// and it throws std::out_of_range in the same case: a variable with no// value.// `std::visit(callable, n.kind)` looks at which type the variant holds right// now and calls the matching lambda with it. Each lambda handles one kind// of node and returns that node's value, calling evaluate again on the// children (`*x.left` follows the unique_ptr to the child Node).// [&] lets a lambda use `values` by reference, without copying the map.// The Number lambda needs nothing from outside, so its [] captures nothing.// Every lambda returns a double, as std::visit requires: one result type.double evaluate(const Node& n, const Variables& values) { return std::visit( overloaded{ [](const Number& x) { return x.value; }, [&](const Variable& x) { return values.at(x.name); }, [&](const Add& x) { return evaluate(*x.left, values) + evaluate(*x.right, values); }, [&](const Multiply& x) { return evaluate(*x.left, values) * evaluate(*x.right, values); }, [&](const Negate& x) { return -evaluate(*x.operand, values); }, }, n.kind);}
// The names of the variables under `n`, each once, sorted. Here the// lambdas return nothing; instead they add to the local set `names`,// which [&] lets them change. For a node with children, each recursive// call returns a new set, and merge moves its names into `names`.Names variables(const Node& n) { Names names; std::visit(overloaded{ [](const Number&) {}, [&](const Variable& x) { names.insert(x.name); }, [&](const Add& x) { names.merge(variables(*x.left)); names.merge(variables(*x.right)); }, [&](const Multiply& x) { names.merge(variables(*x.left)); names.merge(variables(*x.right)); }, [&](const Negate& x) { names.merge(variables(*x.operand)); }, }, n.kind); return names;}- Each operation is one function, with all its cases side by side, instead of a class with five overrides.
- The functions can return a value, so there is no
result_member to keep. All the lambdas in onestd::visitmust return the same type. - A missing case is a compile error (FR-5), just as in the classic form, but the message is much harder to read; see the exercise.
Which form?
Section titled “Which form?”| Question | Classic visitor | std::variant and std::visit |
|---|---|---|
| Where is the list of kinds? | in Visitor, one visit each |
in the std::variant’s template arguments |
| New operation | one new visitor class | one new function |
| New kind of node | a class, a visit in Visitor, one override per visitor |
a struct, a type in the variant, one lambda per operation |
| Forgotten case | compile error, naming the visitor | compile error, deep in the standard library |
| Can code outside add kinds of node? | no, without changing Visitor |
no, without changing the variant |
| Nodes need a common base class? | yes | no; nodes can be plain structs |
| Returning a value from an operation | stored in the visitor, read afterwards | returned directly |
| Cost per node visited | two virtual calls | one std::visit: a lookup on the stored index (a switch or a table of function pointers, depending on the library) |
Prefer the variant when you control the whole list of kinds and the nodes are just data. Prefer the classic form when the elements are already a class hierarchy with behaviour of their own, or when the operations are large enough to want a class each, with their own state and helpers.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same formula, `(x + 2) * -y`, in both forms, with `x = 3`, `y = 4`.{ using namespace classic; // The builder functions each return an ExprPtr. Each result is a // temporary, so it is moved into the call around it: ownership // flows upward until `tree` owns the whole tree. const ExprPtr tree = multiply(add(variable("x"), number(2)), negate(variable("y"))); // *tree is the root node itself, which the operations take by // reference. Three operations, one tree, no change to any node. std::cout << "classic: " << describe(*tree) << " = " << evaluate(*tree, values) << ", variables " << join(variables(*tree)) << '\n';}// The variant form has builders with the same names, so the code that// builds and uses the tree reads exactly the same.{ using namespace alt; const NodePtr tree = multiply(add(variable("x"), number(2)), negate(variable("y"))); std::cout << "variant: " << describe(*tree) << " = " << evaluate(*tree, values) << ", variables " << join(variables(*tree)) << '\n';}before: value -20, variables xclassic: ((x + 2) * -y) = -20, variables x yvariant: ((x + 2) * -y) = -20, variables x yclassic: z has no value- Both forms find both variables (FR-3); the before-version found
only
x. - All three operations agree with each other and across forms:
((x + 2) * -y)with x = 3 and y = 4 is (3 + 2) × −4 = −20 (FR-1, FR-2). - A variable without a value is refused.
values.atthrowsstd::out_of_range, and the last line shows it caught.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `(2 * x) + -y`, with `x = 5` and `y = 1.5`: 10 + -1.5 = 8.5. One tree with// every kind of node, so each operation must handle all five. The value// compares exactly because 8.5 and every step to it are exact in a double.// The extra brackets in LLD_CHECK((...)) are needed because the comma in// Names{"x", "y"} would otherwise split the macro's argument in two.LLD_TEST(each_operation_visits_every_kind_of_node) { using namespace classic; const ExprPtr tree = add(multiply(number(2), variable("x")), negate(variable("y"))); LLD_CHECK_EQ(evaluate(*tree, {{"x", 5.0}, {"y", 1.5}}), 8.5); LLD_CHECK_EQ(describe(*tree), std::string{"((2 * x) + -y)"}); LLD_CHECK((variables(*tree) == Names{"x", "y"}));}
// The formula `-(a + b * 0.5)` built in both forms, with `a = 2`, `b = -3`// (value -0.5). Each operation must give the same answer in both.LLD_TEST(the_classic_and_variant_forms_agree) { const Variables values{{"a", 2.0}, {"b", -3.0}}; const auto c = classic::negate(classic::add(classic::variable("a"), classic::multiply(classic::variable("b"), classic::number(0.5)))); const auto v = alt::negate( alt::add(alt::variable("a"), alt::multiply(alt::variable("b"), alt::number(0.5)))); LLD_CHECK_EQ(classic::evaluate(*c, values), alt::evaluate(*v, values)); LLD_CHECK_EQ(classic::describe(*c), alt::describe(*v)); LLD_CHECK(classic::variables(*c) == alt::variables(*v));}
// A variable with no value makes evaluate throw std::out_of_range, in both// forms. `(void)` throws away the [[nodiscard]] result on purpose. A null// child makes the builder throw std::invalid_argument; nullptr converts to// an empty ExprPtr or NodePtr.// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception.LLD_TEST(a_missing_value_or_operand_is_refused) { LLD_CHECK_THROWS((void)classic::evaluate(*classic::variable("z"), {}), std::out_of_range); LLD_CHECK_THROWS((void)alt::evaluate(*alt::variable("z"), {}), std::out_of_range); LLD_CHECK_THROWS(classic::add(classic::number(1), nullptr), std::invalid_argument); LLD_CHECK_THROWS(alt::negate(nullptr), std::invalid_argument);}
// The tree is built once and evaluated twice with different values: the// operations only read it. `x * x` uses `x` twice, but the set lists it once.LLD_TEST(one_tree_can_be_used_by_many_operations) { using namespace classic; const ExprPtr tree = multiply(variable("x"), variable("x")); LLD_CHECK_EQ(evaluate(*tree, {{"x", 3.0}}), 9.0); LLD_CHECK_EQ(evaluate(*tree, {{"x", -2.0}}), 4.0); LLD_CHECK(variables(*tree) == Names{"x"});}the_classic_and_variant_forms_agree builds the same formula both ways
and checks that every operation gives the same answer in both.
The trade-off
Section titled “The trade-off”Visitor does not make change free; it chooses which change is cheap:
| Change | A virtual function per operation | Visitor (either form) | dynamic_cast chains |
|---|---|---|---|
| Add an operation | every node class changes | one new visitor or function | one new function |
| Add a kind of node | one new class | every operation changes | every function should change |
| A forgotten case | compile error (if the base function is pure virtual) | compile error | nothing: a silent wrong answer |
Making both kinds of change easy at once, without editing existing code and with the compiler still checking every case, is a well-known hard problem, called the expression problem. Visitor is the right side of it when the kinds are stable and the operations keep coming: compilers, formula engines, document formats. If new kinds of node arrive as often as new operations, or from code you do not control (plugins), use virtual functions instead.
When to use it
Section titled “When to use it”- The set of element classes is stable, and you expect to keep adding operations over it.
- The operations are unrelated to each other and to the elements’ main job (printing, checking, exporting), and you do not want each to add a function to every element class.
- You want the compiler to check that every operation handles every kind.
When not to use it
Section titled “When not to use it”- The kinds of element change often. Every new kind changes every visitor.
- There are only one or two operations. A virtual function in each class is simpler and easier to follow.
- Kinds are added by other people, such as plugins. A visitor interface has to list every kind, so code outside cannot add one.
- The operation needs the elements’ private data. A visitor sees only the public interface. Making visitors friends, or adding getters for them, gives away the encapsulation the classes had.
- Two calls per node,
acceptandvisit, and code that is harder to follow in a debugger, since control bounces between the node and the visitor. - Every element needs a public interface for visitors: here,
left(),right(),value(), andname(). - The classic form has nowhere to put a return value, so visitors hold state, which makes them awkward to reuse, and unsafe to share between threads while running.
- Circular dependencies in the classic form: the visitor names every node, and every node names the visitor. Forward declarations handle it, but the two always change together.
Common misuse
Section titled “Common misuse”- A default
visitthat does nothing. A base visitor with empty defaults, so that each visitor overrides only what it needs, is convenient, and it throws away FR-5: a new kind of node is silently skipped, exactly as in the before-version. The same goes for a generic[](const auto&) {}lambda in astd::visitcall. If you want defaults, make each visitor say which kinds it ignores. - A visitor for a hierarchy that keeps growing. Then every kind added is a change to every visitor; use virtual functions.
- Using Visitor to avoid one
dynamic_cast. If one function needs to know about one kind of node, a single cast is simpler than a pattern. - Visiting while changing the tree. A visitor that adds or removes nodes while walking can destroy the node it is in. Build a new tree, or collect the changes and apply them afterwards.
When the requirements change
Section titled “When the requirements change”- “Simplify formulas:
x * 1becomesx.” One new visitor, or one new function in the variant form, which builds and returns a new tree. No node class changes. - “Add division.” A new kind of node: one class, one
visitinVisitor, and one override in each of the three visitors, each found by the compiler. See the exercise. - “Plugins can add their own functions, like
sqrt.” Kinds from outside: a visitor cannot list them. Give the tree a generalCall{name, arguments}node, with the plugin’s code looked up by name, so the list of kinds stays fixed.
Exercise
Section titled “Exercise”Exercise: Add a node type, and count the changes
Add Subtract (a - b) to the formula language, in both forms.
- List every change you must make in the classic form, and in the variant form. Which ones will the compiler find for you if you forget them?
- Now add an operation instead:
count_nodes, which returns the number of nodes in a tree. List the changes in each form again. - In the before-version, what would adding
Subtracttake, and what would the compiler say if you forgotvariables? - What would the compiler say about a missing case in each form? Which message would you rather read?
Show the explained answer
1. In the classic form:
- Declare
class Subtract;beforeVisitor. - Add
virtual void visit(const Subtract& node) = 0;toVisitor. - Write
class Subtract final : public Expr, with a constructor that refuses null operands,left(),right(), andaccept(the usual one line). - Add a builder,
subtract(left, right). - Add
visit(const Subtract&)toEvaluator,Printer, andVariableCollector.
The compiler finds every miss in step 5: once Visitor has the new
pure virtual function, each visitor that lacks it is abstract, and
evaluate, describe, and variables cannot create one. The scratch
build with GCC 11.4 reported, for each, “cannot declare variable
‘evaluator’ to be of abstract type” (and the same for printer and
collector). Steps 1 to 4 are found as soon as you try to use
Subtract.
In the variant form:
- Write
struct Subtract { NodePtr left, right; };. - Add
Subtractto the variant inNode. - Add a builder,
subtract(left, right). - Add a
Subtractlambda to thestd::visitcall inevaluate,describe, andvariables.
The compiler finds every miss in step 4: a std::visit call whose
callable cannot accept a Subtract does not compile.
2. Classic: one new visitor class (with five visit functions)
and one function count_nodes that runs it. Variant: one function with
one std::visit call and five lambdas. In neither form does any node
change. A sketch of the variant form:
// How many nodes the tree under n has, counting n itself.std::size_t count_nodes(const Node& n) { return std::visit( overloaded{ // A leaf is one node. `-> std::size_t` sets the return type, // so it matches the other lambdas (see below). [](const Number&) -> std::size_t { return 1; }, [](const Variable&) -> std::size_t { return 1; }, // A node with children: itself, plus the count of each child. // 1 + a std::size_t is a std::size_t, so no `->` is needed here. [](const Add& x) { return 1 + count_nodes(*x.left) + count_nodes(*x.right); }, [](const Multiply& x) { return 1 + count_nodes(*x.left) + count_nodes(*x.right); }, [](const Negate& x) { return 1 + count_nodes(*x.operand); }, }, n.kind);}The -> std::size_t on the first two lambdas matters: 1 alone is an
int, and every lambda in one std::visit must return the same type. Alternatively, name the result type once, as std::visit<std::size_t>(…) (C++20), which converts each lambda’s result to it.
3. The before-version needs a new class and a new if in each
function. Forget one, and the compiler says nothing: that is what
happened to Negate in variables.
4. The classic form’s message names the visitor that is missing a
function: cannot declare variable 'evaluator' to be of abstract type 'classic::{anonymous}::Evaluator'. The variant form’s message, in the same scratch build,
began deep in the standard library: no type named 'type' in 'struct std::invoke_result<…overloaded<…>…, const alt::Subtract&>', followed by more errors from inside <variant>. It does name
Subtract and the function, but you have to look for them. Most
people would rather read the first one; the variant form’s advantages
are elsewhere.
Related patterns
Section titled “Related patterns”- Composite: the structure a visitor most often walks. Composite gives the tree; Visitor adds operations over it without growing the node classes. See Composite.
- Interpreter: a tree whose nodes are a grammar’s rules. Its operations (evaluate, describe) can be visitors when there are many of them. See Interpreter.
- Iterator: decides the order of elements; a visitor decides what to do with each one. They combine when a structure is walked in a fixed order and each element is visited. See Iterator.
Summary
Section titled “Summary”- Visitor moves each operation on a stable set of classes into a class
of its own, with one
visitfunction per kind of element. - Double dispatch picks the code from two types:
acceptis virtual on the element, andvisitis virtual on the visitor, called with the element’s exact type. - New operations become one class; new kinds of element change every visitor, but the compiler finds each one.
- In modern C++, a
std::variantof plain structs withstd::visitgives the same trade-off with less code, when you own the whole list of kinds. - Do not add default “do nothing” cases: they bring back the silent misses that Visitor exists to prevent.