liveBook · Manning

Overload helper

As explained in Learn C++ by Example

An overload helper is a class template that combines call operators from multiple lambda or callable base objects into one callable object.

An overload helper combines several lambdas into one callable object. It inherits from each lambda and brings every operator() into scope, making it a convenient visitor for std::variant. section 9.3.5

The pattern has a small set of moving parts:

  • C++17 requires a deduction guide; C++20 can deduce the types directly. section 9.3.5

Dispatching reel actions

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); Each alternative receives its matching lambda, while a missing alternative becomes a compile-time error. section 9.3.5

How Learn C++ by Example covers it

How deep it goes
Builds the helper from inherited lambdas, operator() pack expansion, deduction guides, and a working reel example.
Examples
Demonstrates Hold, Nudge, and Spin actions that leave, rotate, or randomly rotate a reel.
What it assumes
Assumes lambdas, callable operator(), class templates, parameter packs, and std::variant basics.
What you can do after
Apply it via std::visit to create compile-time-checked visitors for several variant alternatives.
How it connects
Connects lambda expressions, callable objects, parameter packs, class templates, std::variant, and std::visit.

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.