liveBook · Manning

Std::visit

As explained in Learn C++ by Example

std::visit is a C++ standard library function template that invokes a callable with the currently held alternative of one or more std::variant objects.

std::visit invokes a callable with the value currently held by one or more std::variant objects. The callable must handle every possible alternative, so missing cases become compile errors instead of overlooked branches. section 9.3.5

A typical use follows this pattern:

  • Define a callable with an overload for each variant alternative. section 9.3.5
  • Pass the callable and variant to std::visit. section 9.3.5
  • Combine lambdas with the Overload pattern when each alternative needs different behavior. section 9.3.5

Choosing a slot-machine action

A variant containing Hold, Nudge, or Spin can be handled without a chain of std::holds_alternative checks: auto RollMethod = Overload{ [](Hold) {}, [&reel](Nudge) { std::rotate(reel.begin(), reel.begin() + 1, reel.end()); }, [&reel, &random_fn](Spin) { std::rotate(reel.begin(), reel.begin() + random_fn(), reel.end()); } }; std::visit(RollMethod, opt); section 9.3.5

template <class R, class Visitor, class... Variants>
constexpr R visit( Visitor&& vis, Variants&&... vars );

Use the compact signature to inspect std::visit's return type, visitor, and parameter-pack variants. section 9.3.5

How Learn C++ by Example covers it

How deep it goes
Explains callable dispatch, compile-time alternative checking, multiple variants, and the Overload pattern, but not implementation internals.
Examples
Uses Hold, Nudge, and Spin actions to rotate slot-machine reels.
What it assumes
Assumes std::variant and lambdas while teaching parameter packs and callable overload composition.
What you can do after
Build it from scratch by dispatching variant alternatives with overloaded functions or lambdas.
How it connects
Connects std::variant and std::holds_alternative with lambdas, parameter packs, the Overload pattern, and std::views::zip.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.