liveBook · Manning

Parameter pack

As explained in Learn C++ by Example

A parameter pack is a template parameter or function parameter representing zero or more arguments of potentially varying types.

A parameter pack represents zero or more template or function arguments, which may have varying types. An ellipsis marks the pack, while its position changes how the arguments are declared or expanded. Variadic templates contain at least one parameter pack. section 9.3.1 section 5.2.3

Recognize parameter packs in three common positions:

  • `typename... Ts` declares zero or more template types; `Ts...` declares a function parameter pack. section 9.3.1
  • Use an ellipsis again to unpack arguments, either with a fold expression such as `(... + tail)` or inside an initializer list. section 9.3.1 section 9.3.2
  • C++11 required recursive unpacking; C++17 fold expressions provide a shorter alternative. section 9.3.1

Adding an arbitrary number of values

A variadic `add` function accepts one or more values and folds them with `+`: `template<typename... Ts> auto add(const Ts&... tail) { return (... + tail); }`. Calls such as `add(1, 2, 3)` produce `6`; an empty call can be supported with an initial value, as in `(0 + ... + tail)`. The same technique can concatenate strings. section 9.3.1

Counting reel frequencies

A general-purpose `frequencies` function accepts varying numbers convertible to `int`, expands them into `{ static_cast<int>(numbers)... }`, and counts them in a map. The slot machine passes its left, middle, and right digits, while the same function could support additional reels. section 9.3.2

Listing 9.11 Fold example
template<typename... Ts>      #1
auto add(const Ts&... tail)   #2
{
    return (... + tail);      #3
}

Inspect the complete fold-expression example to see declaration, parameter-pack placement, expansion, and invocation together. section 9.3.1

How Learn C++ by Example covers it

How deep it goes
Defines pack declaration and expansion, then demonstrates folds and initializer lists; defers broader template internals.
Examples
Demonstrates addition, string concatenation, slot-machine frequency counting, and grouped Hold, Nudge, and Spin handlers.
What it assumes
Assumes STL and std::variant familiarity, then teaches parameter-pack declaration and expansion through small working examples.
What you can do after
Builds variadic functions that accept, constrain, expand, and combine varying numbers of arguments.
How it connects
Connects parameter packs with variadic templates, fold expressions, concepts, std::variant, std::visit, lambdas, and the Overload pattern.

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.