In C++, how does std::visit with the overloaded-lambdas idiom handle every alternative of a std::variant, and what goes wrong with it?
answer
- inherit from every lambda
- a using-declaration with a pack
- a deduction guide C++20 made optional
- implicit conversions pick a lambda
- one return type for all
basics
~20 sstd::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#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
Know that std::visit calls a function with the active alternative and that the overloaded helper combines several lambdas into one visitor.
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.
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.
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