Language[lang]

std::visit Explained: Calling Handlers for Variant Types

Abstract

std::visit is a C++ function that calls a handler for the active value in a std::variant, a type-safe object that holds exactly one of a fixed list of types. Write a visitor for every alternative to let the compiler catch missing cases; visiting multiple variants requires handling every combination, and a valueless variant can make the call throw. It suits closed sets of types, while virtual functions are often a better fit when types need to remain open-ended.

Ink drawing of a workshop bench with three chutes; only one is marked vermilion and aligned with a lever, showing the single correct path.
Figure 1 — Ink drawing of a workshop bench with three chutes; only one is marked vermilion and aligned with a lever, showing the single correct path.

Picture a mail room sorting parcels into bins: letters one way, boxes another, tubes a third.

The sorter only ever holds one parcel at a time, and that’s the idea behind a std::variant, a type-safe union that holds exactly one of its listed types. std::visit is the sorter: it checks what the variant holds and calls the handler written for that type.

We’ll cover how to call it, the visitor styles you’ll meet, multi-variant visits, and the pitfalls that are easy to miss, noting which standard introduced each technique.

Sum Types and Std::variant Basics for Std::visit

Before you visit a value, you need a type that says what’s inside it, and we’ll start there.

What a sum type or variant is

A sum type holds exactly one of several alternatives and knows which one is active. The hand-built version is a tagged union (also called a discriminated union): a tag records the active alternative beside the storage.

Unlike a product type such as a struct, which holds every field at once, a sum type holds one alternative. std::variant is C++17’s type-safe union: std::variant<int, std::string> holds an int or a string, never both.

Why hand-rolled alternatives cause trouble

Before std::variant, you wrote this pattern by hand, and it came with five traps:

  • Manual tag and union upkeep. The tag and the union must stay in sync by hand.
  • Error-prone invalid fields. Reading the wrong member is undefined behavior, and nothing stops you.
  • Constructor and destructor management. You construct and destroy each member yourself.
  • Polymorphism needs heap allocation. Class-hierarchy alternatives usually live on the heap behind pointers.
  • dynamic_cast and ownership issues. Type checks become dynamic_cast chains, and every pointer raises the question of who owns the object.

What std::variant gets you

  • Value semantics preserved. A variant copies and moves like any other value.
  • No heap allocation. The alternative lives in the variant’s own storage, so the variant never touches the heap.
  • No raw pointers. There’s nothing to new or delete.
  • Makes invalid states unrepresentable. The variant always names one active alternative.

Consider a game engine programmer whose network layer handles chat lines, position updates, and disconnects. A hand-rolled union would need a new enum value, a union member, and copy and destructor code for each new message type.

With std::variant, it’s one more template argument. That’s a smaller diff to review.

A split drawing contrasts a chaotic pile of mechanical parts on the left with an organized device featuring interchangeable inserts on the right.
Figure 2 — A split drawing contrasts a chaotic pile of mechanical parts on the left with an organized device featuring interchangeable inserts on the right.

Other C++17 types worth knowing

  • std::optional is a missing-value wrapper: std::optional<T> holds a T or nothing.
  • std::any holds any copyable type, trading compile-time checks for flexibility. Asking for the wrong type with std::any_cast throws std::bad_any_cast.
  • In-place construction: std::variant accepts std::in_place_type<T>, and std::optional accepts std::in_place, so the value is built directly in storage with no temporary to copy.
  • C++17 feature overview: std::variant, std::optional, and std::any all arrived in C++17, in the <variant>, <optional>, and <any> headers. std::visit lives in <variant> too.

What Is Std::visit and When to Use It?

Use std::visit when a value could be one of several types and you need code for whichever one it holds.

Calling a visitor on a variant

A variant holds one value from a fixed list of types. std::visit takes a visitor plus a variant and calls the visitor with the active alternative. The visitor must be callable for every alternative.

The std:: prefix names the standard library’s namespace, so std::visit is the version your compiler ships. It arrived with std::variant in C++17.

Instead of a chain of holds_alternative checks and get calls, you make one call. A game engine programmer might store input events as a variant of KeyPress, MouseMove and WindowResize, with one overload per type.

When a teammate adds a fourth type, the build fails until the visitor handles it. The compiler does the reminding.

Two newer forms: you can name the return type, as std::visit<double>(visitor, v), and a member form, v.visit(visitor), is headed for C++26, so check your compiler first.

A throwing assignment can leave a variant valueless_by_exception, and visiting it throws std::bad_variant_access. Check valueless_by_exception() first when assignment can fail.

Visiting several variants at once

Pass several variants and the visitor gets one alternative from each, so it must handle every combination: two three-alternative variants need nine branches. A vector of variants is just a loop, with one call per element.

Every call must return one type. If one alternative returns an int and another a std::string, we’d get a compile error unless you name the return type.

Returning values and capturing state

The result is whatever the visitor returned, so you assign it like any function result. A lambda can capture by reference, letting the visitor add to a running total without a global.

Take the parameter as auto& and the visitor can change the value an alternative holds, but not its type.

Where pattern matching fits in C++

Rust-style match syntax, which picks a branch for each variant, isn’t in C++17, so a visitor is the closest you get. The C++ standards committee’s paper P0095R1, Pattern Matching and Language Variants proposed pattern matching for C++.

Whether a later standard adopts it is up to the committee, so std::visit is your tool for now.

Different Ways to Write a Visitor

A visitor is the callable you pass to std::visit. Here are four common ways to write one:

A struct with overloaded call operators

The most direct style is a struct with one operator() per alternative. The cost is boilerplate: a named struct and an overload for every case, even one-line bodies.

A templated catch-all overload accepts any type, so the build stays green, but it switches off exhaustiveness: the rule that every alternative needs a handler.

Consider a game engine programmer with a std::variant<Click, KeyPress, Resize> who later adds Scroll. With the catch-all, Scroll quietly falls into the template, and you’ll only find out at runtime. Without it, a missing overload is a compile error.

The compiler checks every alternative, not most of them.

A steel blue and vermilion ink drawing shows a conveyor belt sorting capsules, with one falling into a pit while others are caught by hooks.
Figure 3 — A steel blue and vermilion ink drawing shows a conveyor belt sorting capsules, with one falling into a pit while others are caught by hooks.

Combining lambdas with a small helper

Lambdas are shorter than a struct, so many codebases merge inline lambdas with a small overload helper. In C++17 it’s template<typename... Ts> struct overloaded : Ts... { using Ts::operator()...; };.

Variadic template inheritance makes each lambda a base, and the using declaration pulls every operator() into one scope.

C++17 also needs a deduction guide so overloaded{lambda1, lambda2} can deduce Ts: template<typename... Ts> overloaded(Ts...) -> overloaded<Ts...>;. The standard library doesn’t provide this helper.

Before C++17, you couldn’t expand the pack in a using-declaration, so you wrote a recursive make_visitor, one level per lambda.

C++20 removes the guide, not the helper: aggregate deduction works out Ts for overloaded{lambda1, lambda2} on its own.

Using one generic lambda for all types

When every alternative gets the same treatment, one generic lambda does the job: std::visit([](auto&& x) { ... }, v);. It suits logging the type with typeid, summing a value every alternative supports, or modifying the stored value in place (take auto& for that).

The catch: it accepts everything, so exhaustiveness doesn’t apply here, and an unsupported type fails deep inside the body.

Branching on type with if constexpr

When one lambda needs different code per type, branch at compile time with if constexpr. Because auto&& deduces a reference, strip it with using T = std::decay_t<decltype(x)>; and then test std::is_same_v<T, int>.

The branch that doesn’t match is discarded, so it never has to compile for that alternative. One lambda, one place to read.

How the Visitor Pattern Relates to Polymorphism

The visitor pattern and std::visit solve the same problem: different code for each type.

The classic Gang of Four visitor

The original pattern uses inheritance and virtual methods. Each element has an accept function that takes a visitor.

Calling accept, then visit, is double dispatch, since C++ can’t dispatch on two types at once. The cost is two class hierarchies, one for elements and one for visitors.

A parser with Literal, Add and Negate nodes must update every visitor for each new node.

Using std::visit to implement a visitor

std::visit swaps the hierarchy for a variant. It dispatches on the variant’s active alternative at runtime, much like a virtual call.

Overload resolution happens at compile time: pass overloaded lambdas, and the compiler matches each alternative to an overload. Leave one out with no catch-all, and the build fails.

The overloaded helper is a struct that inherits from several lambdas. It works in C++17, and since C++20, class template argument deduction (CTAD) lets you skip the deduction guide.

The variant is also the data being visited, so its alternatives form one closed list.

A hexagonal vermilion cartridge is stamped by a steel blue press head, while other shapes remain idle on the bench.
Figure 4 — A hexagonal vermilion cartridge is stamped by a steel blue press head, while other shapes remain idle on the bench.

Choosing between compile-time and runtime polymorphism

  • Strategy via std::for_each. A game engine calls std::for_each over a std::vector of shapes, and std::visit handles each one. A new shape adds one alternative and one overload, and the compiler flags any visitor that misses it.
  • Different trade-offs. Visit makes operations easy to add, while virtual functions make types easy to add.
  • Choose the appropriate tool. Ask which change you’ll make more often. Closed types suit std::visit; open types, like plugins, suit virtual functions.
  • Dispatch cost: table versus virtual call. Common std::visit implementations index a table of function pointers, similar in cost to a virtual function table (vtable) lookup. Measure first.

Why the C++ Approach Feels so Complicated

If you’ve wondered why std::visit needs so much setup, you’re not alone. The complexity has causes we can name.

The burden of added complexity

A developer whose team stores messages in a std::variant, a type holding one of several listed types, wants to log each one.

The logic is a few lines, but the first version needs a visitor, a callable you write for each type, plus template knowledge to read the errors. The task is simple; the setup isn’t.

That setup hits beginners hardest, since teaching std::visit means teaching templates first.

Visitor styles add verbosity: generic lambdas, structs with an operator() per type, and overloaded lambdas all work, but mixing them makes every reviewer relearn the pattern.

Where the standards committee is heading

The committee’s push to catch up with other languages is a fair goal. The trouble is accidental complexity: each addition solves a real problem, but the pieces interact.

A tech lead reviewing a pull request sees a helper template, three lambdas and a struct wrapping one visit, and most of the diff is scaffolding. Teammates from Rust or D often notice the gap first.

Whether variant still earns its place

Despite the friction, std::variant still earns its place when a value is one of a closed set of types.

A game engine programmer whose input events are a variant of click, key press and resize structs gets a useful check: a new event type makes the compiler flag any visitor that can’t handle it.

Seen that way, std::visit is a great step toward pattern matching. Learn the habit now, and the next step feels familiar.

std::visit pairs a variant that holds one value at a time with a visitor that handles each type it might hold. Pick the visitor style that fits your codebase, confirm which standard your compiler targets, and let the compiler flag any case you’ve missed.

The variant holds the data, and std::visit makes sure every case gets handled.

References

  1. Pattern Matching and Language Variants — open-std.org

Questions

What is std in coding?

In C++, `std` is the namespace that contains names from the C++ standard library, such as `std::string`, `std::vector`, and `std::visit`. The `std::` prefix identifies a name as coming from that library.

When to use std :: in C++?

Use `std::` when referring to a C++ standard library name, such as `std::cout`, `std::vector`, or `std::visit`. It makes the name explicit and avoids relying on a `using` declaration that could cause name conflicts.

Read next

  1. C++ functions: syntax, calling and overloadingLanguage · Miriam Castellanos · written for C++17
  2. Data types in C++: int, double, char, bool and moreLanguage · Miriam Castellanos · written for C++17
  3. Const Variable Explained: What It Is and How to Use ItLanguage · Miriam Castellanos