skip to content

Variant and Any

std::variant is a type-safe tagged union visited with std::visit, and std::any holds anything behind type erasure. Interviewers ask when variant beats a virtual hierarchy.

on this pageshow

explore

questions

5

In C++, how does std::visit with the overloaded-lambdas idiom handle every alternative of a std::variant, and what goes wrong with it?

level: middleimportance: must knowfreq 58%

answer

  1. inherit from every lambda
  2. a using-declaration with a pack
  3. a deduction guide C++20 made optional
  4. implicit conversions pick a lambda
  5. one return type for all

basics

~20 s

std::visit calls the visitor with the active alternative. The overloaded idiom builds one visitor from several lambdas by inheriting their call operators, so a missing case fails to compile; implicit conversions and catch-all generic lambdas can still route alternatives silently.

solid answer

~40 s

`std::visit(vis, v)` invokes `vis` with the value currently in `v`, so the visitor must be callable with **every** alternative; that is checked at compile time. The idiom is a three-line helper: `template<class... Fs> struct overloaded : Fs... { using Fs::operator()...; };`, which inherits from each lambda and pulls all their `operator()`s into one overload set. In C++17 it also needs a deduction guide, `template<class... Fs> overloaded(Fs...) -> overloaded<Fs...>;`; C++20's class template argument deduction for aggregates makes the guide unnecessary. Overload resolution then picks a lambda per alternative, which is where the traps are: a `bool` alternative with no lambda of its own silently matches an `int` lambda, and a generic `[](const auto&)` catch-all hides a newly added alternative. All calls must also return the same type and value category, unless C++20's `std::visit<R>` names one.

code

cpp · 27 lines
cpp
#include <iostream>
#include <string>
#include <variant>
#include <vector>

template <class... Fs> struct overloaded : Fs... { using Fs::operator()...; };
template <class... Fs> overloaded(Fs...) -> overloaded<Fs...>;   // needed in C++17 only

using Json = std::variant<std::monostate, bool, double, std::string>;

int main() {
    std::vector<Json> values{Json{}, true, 3.5, std::string("hi")};
    for (const Json& v : values) {
        std::cout << v.index() << ": ";
        std::visit(overloaded{
            [](std::monostate) { std::cout << "null\n"; },
            [](bool b) { std::cout << (b ? "true" : "false") << '\n'; },
            [](double d) { std::cout << d << '\n'; },
            [](const std::string& s) { std::cout << '"' << s << "\"\n"; },
        }, v);
    }
    Json j = 2.0;
    if (const double* d = std::get_if<double>(&j)) std::cout << "double " << *d << '\n';
    std::cout << std::holds_alternative<std::string>(j) << '\n';
    try { (void)std::get<std::string>(j); }
    catch (const std::bad_variant_access&) { std::cout << "bad_variant_access\n"; }
}

go deeper

for a junior

Know that std::visit calls a function with the active alternative and that the overloaded helper combines several lambdas into one visitor.

for a middle

Explain the helper line by line: inheritance from each lambda, the pack using-declaration, and the C++17 deduction guide that C++20 no longer needs.

for a senior

Spot the silent traps: implicit conversions routing alternatives to the wrong lambda, catch-alls hiding new alternatives, and the single-return-type rule with visit<R> as the escape.

for a principal

Decide on a house style for visitation, such as exact-type lambdas or if constexpr with a static_assert, so adding an alternative always breaks the build where it must.

## What std::visit does `std::visit(visitor, variants...)` (C++17, `<variant>`) looks at the active alternative of each variant and calls `visitor` with it. For a single variant the draft requires the dispatch to take **constant time**, independent of the number of alternatives; implementations typically use a table of function pointers. If the variant is valueless, `visit` throws `std::bad_variant_access`. Two compile-time rules come from the draft's **Mandates**: 1. The visitor must be **invocable with every alternative**. libc++ reports a gap with the static assertion text ``std::visit` requires the visitor to be exhaustive``. 2. All those calls must have **the same type and value category**. A visitor returning `int` for one alternative and `double` for another fails; libc++ says ``std::visit` requires the visitor to have a single return type``. C++20 adds `std::visit<R>(vis, v)`, which converts every result to `R`. ## The overloaded-lambdas idiom A visitor is usually one callable per alternative. Rather than writing a struct with several `operator()`s, the idiom assembles one from lambdas: ```cpp template <class... Fs> struct overloaded : Fs... { using Fs::operator()...; }; template <class... Fs> overloaded(Fs...) -> overloaded<Fs...>; // C++17 only ``` - `struct overloaded : Fs...` inherits from every lambda's closure type. - `using Fs::operator()...;` is a C++17 pack expansion in a using-declaration that brings all the call operators into one scope, so they overload instead of hiding each other. - The **deduction guide** tells C++17 how to deduce `Fs...` from `overloaded{lambda1, lambda2}`. C++20 deduces template arguments for aggregates directly, so the guide can go; under `-std=c++17` without it, clang reports `no viable constructor or deduction guide for deduction of template arguments of 'overloaded'`. The helper is not in the standard library; every codebase writes these lines itself. ## Where it goes wrong | Trap | What happens | Fix | |---|---|---| | Implicit conversion | a `bool` alternative is handled by an `int` lambda; a run printed `int 1` for `true` | add a lambda for every alternative, or use `if constexpr` on the exact type | | Generic catch-all | `[](const auto&) {}` matches a newly added alternative, so the compiler cannot flag it | keep catch-alls for truly uniform cases, or `static_assert` inside them | | Mixed return types | compile error on the single-return-type rule | make every lambda return the same type, or use `std::visit<R>` | | Capturing by reference | a visitor stored for later can outlive what it captured | visit immediately, capture by value when stored | The conversion trap deserves emphasis because it compiles cleanly. With `std::variant<int, bool, std::string>` and lambdas for `int` and `const std::string&` only, a `bool` value promotes to `int`, and overload resolution picks the `int` lambda without a warning. ## The alternative: one generic lambda with if constexpr ```cpp std::visit([](const auto& x) { using T = std::decay_t<decltype(x)>; if constexpr (std::is_same_v<T, bool>) { /* ... */ } else if constexpr (std::is_same_v<T, int>) { /* ... */ } else static_assert(sizeof(T) == 0, "unhandled alternative"); }, field); ``` This matches exact types only and turns an unhandled alternative into a compile error. The condition `sizeof(T) == 0` depends on `T`, so the assertion fires only in a branch that is actually instantiated. ## Visiting several variants at once `std::visit` accepts more than one variant: `std::visit(vis, a, b)` calls `vis(x, y)` with the active alternatives of both, so the visitor must handle **every combination**. For two variants of three alternatives each that is nine call signatures, which generic lambdas usually cover. The constant-time guarantee applies only to a single variant; for several, the draft sets no complexity requirement, and the combinations grow multiplicatively in both compile time and code size. ## Member visit in C++26 C++26 adds `v.visit(vis)` as a member function declared with an explicit object parameter, plus `v.visit<R>(vis)`. It behaves like `std::visit` applied to that one variant. Apple clang 21 with libc++ already accepts it under `-std=c++2c`, but portable code in 2026 still writes `std::visit`.

  • Why does the overloaded struct need using Fs::operator()...;?
    Without it, each base class's `operator()` is a member of a different base, and name lookup in the derived struct finds the name in several bases, so the call is ambiguous rather than overloaded. The using-declaration brings every call operator into the derived class's scope as one overload set, letting normal overload resolution pick the best match per alternative.
  • How do you return different types from different branches of a visit?
    Either make every branch return one common type, such as a `std::string` description, or, since C++20, call `std::visit<R>(vis, v)`, which converts each result to `R`. Without either, the draft mandates that all invocations have the same type and value category, and the call does not compile.

  • std::visit silently skips alternatives the visitor cannot handle
  • The overloaded helper is a class provided by the standard library
  • A bool alternative can only ever match a lambda taking bool
  • A catch-all auto lambda keeps the visitor exhaustive and safe for new alternatives
  • std::visit searches the alternatives linearly, so dispatch slows with more alternatives
open as a page

In C++17, how do you find out which alternative a std::variant holds and read it without risking an exception?

level: juniorimportance: should knowfreq 52%

basics

~10 s

Ask index() for the zero-based alternative or holds_alternative<T>(v) for a type test, then read with std::get_if<T>(&v), which returns nullptr on a mismatch. std::get<T>(v) throws std::bad_variant_access when v holds another alternative.

open as a page

In C++17, what can a std::any hold, and how does std::any_cast behave when the requested type does not exactly match?

level: middleimportance: should knowfreq 32%

basics

~20 s

std::any holds one value of any copy-constructible type. std::any_cast<T> must name the exact stored type: the value form throws std::bad_any_cast on a mismatch, and the pointer form any_cast<T>(&a) returns nullptr. No conversions apply, so int is not long.

open as a page

When can a C++ std::variant become valueless_by_exception, and what do index(), std::get and std::visit do afterwards?

level: seniorimportance: should knowfreq 33%

basics

~10 s

A variant may become valueless when a type-changing emplace or assignment throws after the old alternative was destroyed. Then index() returns std::variant_npos, and std::get and std::visit throw std::bad_variant_access until a new value is assigned.

open as a page

For a JSON value type in C++, when should you model it as a std::variant instead of a virtual class hierarchy, and what does each choice cost?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Use std::variant when the set of kinds is closed, like JSON's six kinds: values live in place without per-node heap allocation, and visitation flags missing cases. Use a virtual hierarchy when new kinds must be added independently.

open as a page