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
