liveBook · Manning

Fold expression

As explained in Learn C++ by Example

A fold expression is a C++ expression that applies an operator across the elements of a parameter pack.

A fold expression applies an operator across the elements of a parameter pack. C++17 replaces the recursive unpacking required in C++11 with a compact expression such as (... + tail). section 9.3.1

Summing a parameter pack

template<typename... Ts> auto add(const Ts&... tail) { return (... + tail); } accepts values of potentially different deduced types. Calling add(1, 2, 3) produces ((1 + 2) + 3), while placing the dots on the other side produces (1 + (2 + 3)).

How Learn C++ by Example covers it

How deep it goes
Explains pack declaration, function parameters, operators, association, and empty-pack initialization, but does not detail every fold form.
Examples
Demonstrates integer sums, subtraction, empty calls, string concatenation, and left- versus right-associative grouping.
What it assumes
Assumes parameter-pack syntax while explaining pack declarations, function tails, and compiler-deduced return types.
What you can do after
Apply it via C++17 fold syntax to replace recursive parameter-pack unpacking with concise variadic operations.
How it connects
Connects parameter packs, variadic templates, template argument deduction, recursion, and operator associativity.

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.