Skip to content

Visitor

Difficulty: Advanced

Key concepts

  • visitor pattern
  • double dispatch
  • std::variant
  • std::visit
  • expression problem
  • 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::variant with std::visit, and when to prefer it.

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.

  1. FR-1 Evaluate a formula, given values for its variables.
  2. FR-2 Show a formula as text, with explicit grouping.
  3. FR-3 List the variables a formula uses, so that a form can ask for their values.
  4. 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.
  5. FR-5 When a new kind of node is added, every operation must handle it, and forgetting one must not go unnoticed.

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).

before.hpp
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 later
public:
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 updated

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// 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).

main.cpp
// `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. Negate was added after variables was written. evaluate was updated and variables was not, and nothing said so: an unknown node falls through the if chain 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_cast per 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).

test_visitor.cpp
// 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).

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 visit function per kind of element. Here, Visitor, with five.
  • Concrete visitors: one per operation. Here, Evaluator, Printer, and VariableCollector.
  • The element interface: one function, accept, that takes any visitor. Here, Expr.
  • Concrete elements: the node classes. Each implements accept by calling visitor.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.

Nodes accept any Visitor; each operation is one Visitor class with a visit function per kind of node
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 visit

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

classic.hpp
// 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 that visit can take them by reference. Visitor is the one place that lists every kind of node.
  • visit is overloaded on the node type. All five functions have the same name; the compiler picks one by the static type of the argument.
  • accept takes a non-const Visitor& because visitors build their results as they go; it is itself const because visiting does not change the tree.
  • Visitor’s copy operations are protected, so a = b, with both declared as Visitor&, does not compile; it would copy only the Visitor part (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).

classic.hpp
// 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.

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:

  1. node.accept(visitor) is a virtual call on the node, so it runs, say, Multiply::accept.
  2. Inside it, the type of *this is known at compile time, so overload resolution picks visit(const Multiply&). That call is virtual on the visitor, so at run time it runs, say, Printer::visit(const Multiply&).
Describing -y: two virtual calls pick Printer's code for Negate, then the same again for the child
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"

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

classic.hpp
// 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).

classic.cpp
// 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.

  • visit returns void, 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 helper of turns “visit, then read the result” into an expression. In of(left) + of(right), the two calls may run in either order, and each overwrites result_, but each returns its own copy first, so the sum is right.
  • Evaluator holds a reference to the values. It is safe because an Evaluator lives only inside evaluate, below, while the caller’s Variables exists.
  • The visitor walks the children itself. The nodes’ accept does not visit children. That lets each operation choose the order, as Printer does (left, operator, right), or skip parts.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

classic.cpp
// 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).

classic.cpp
// 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 null
  • const 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() call
  • double result_;

Member functions

  • explicit Evaluator(const Variables& values);
  • double result() const;
  • void visit(const Add& node) override; and one for each other kind
The visitor interface, one node, and one operation

The outline leaves out Number, Variable, Negate, the other two visitors, and the functions that build trees (number, add, and so on).

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).

variant_form.hpp
// 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 Add still holds its children through std::unique_ptr, and Node is declared first so that NodePtr can name it. Node is a struct around the variant, not a using alias, 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).

variant_form.cpp
// 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).

variant_form.cpp
// 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 one std::visit must 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.
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).

main.cpp
// 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';
}
Expected output
before: value -20, variables x
classic: ((x + 2) * -y) = -20, variables x y
variant: ((x + 2) * -y) = -20, variables x y
classic: 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.at throws std::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).

test_visitor.cpp
// `(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.

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.

  • 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.
  • 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, accept and visit, 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(), and name().
  • 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.
  • A default visit that 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 a std::visit call. 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.
  • “Simplify formulas: x * 1 becomes x.” 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 visit in Visitor, 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 general Call{name, arguments} node, with the plugin’s code looked up by name, so the list of kinds stays fixed.

Exercise: Add a node type, and count the changes

Add Subtract (a - b) to the formula language, in both forms.

  1. 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?
  2. Now add an operation instead: count_nodes, which returns the number of nodes in a tree. List the changes in each form again.
  3. In the before-version, what would adding Subtract take, and what would the compiler say if you forgot variables?
  4. 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:

  1. Declare class Subtract; before Visitor.
  2. Add virtual void visit(const Subtract& node) = 0; to Visitor.
  3. Write class Subtract final : public Expr, with a constructor that refuses null operands, left(), right(), and accept (the usual one line).
  4. Add a builder, subtract(left, right).
  5. Add visit(const Subtract&) to Evaluator, Printer, and VariableCollector.

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:

  1. Write struct Subtract { NodePtr left, right; };.
  2. Add Subtract to the variant in Node.
  3. Add a builder, subtract(left, right).
  4. Add a Subtract lambda to the std::visit call in evaluate, describe, and variables.

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.

  • 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.
  • Visitor moves each operation on a stable set of classes into a class of its own, with one visit function per kind of element.
  • Double dispatch picks the code from two types: accept is virtual on the element, and visit is 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::variant of plain structs with std::visit gives 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.