9 Parameter packs and std::visit

 

This chapter covers

  • Practicing with algorithms and execution policies
  • Template parameter packs
  • The std::visit method and Overload pattern
  • Mutable lambdas
  • Extra practice with variants, std::format, and ranges

We have used parameter packs (the three dots in a template) several times now, but we have not paused to understand how they work. In the final chapter, we will fill in the dots, as well as practice many things we have learned so far. We will generate triangle numbers and briefly consider some of their properties. Triangle numbers crop up in various places (e.g., counting how many handshakes would happen in a group of people if everyone shakes hands). Because we started with Pascal’s triangle, returning to a number sequence feels like a good way to round off.

We’ll discover we can create triangle numbers in a couple of lines of code using numeric algorithms, and then we will build a slot machine using the first few triangle numbers. We will build a simple machine first, which only spins the reels. We will then improve the game, allowing holds, nudges, or spins. To implement these options, we will learn about std::visit and the Overload pattern. We will practice what we have learned in previous chapters, which will help us write more C++ using new features, being confident we can keep up to date with any future changes.

9.1 The triangle numbers

9.1.1 Testing our triangle numbers with algorithms

9.1.2 Execution policies for algorithms

9.1.3 Mutable lambdas

9.1.4 More properties of the triangle numbers

9.2 A simple slot machine

9.2.1 Revision of constexpr and std::format

9.2.2 Using std::rotate to spin the reels

9.2.3 The simple slot machine

9.3 A better slot machine

9.3.1 Parameter packs and fold expressions