liveBook · Manning

Unary fold

As explained in Learn C++ by Example

A unary fold is a fold expression that combines a parameter pack with an operator without an explicit initial value.

A unary fold combines every element in a parameter pack with an operator, without an explicit initial value. With +, (... + tail) expands a pack into a left-associative expression; (tail + ...) produces a right fold. section 9.3.1

Adding a parameter pack

template<typename... Ts> auto add(const Ts&... tail) { return (... + tail); } works for add(1, 2, 3) and add(1), but fails for add() because a unary fold over + requires a nonempty pack. Associativity matters for non-associative operators: subtraction gives different results on the left and right. section 9.3.1

Important constraints and alternatives:

  • Use a binary fold when an empty pack must be supported, such as (0 + ... + tail). section 9.3.1
  • Any operator that applies to the parameters can be used, including operator+ for strings. section 9.3.1
Listing 9.11 Fold example
template<typename... Ts>      #1
auto add(const Ts&... tail)   #2
{
    return (... + tail);      #3
}

View the compact C++ implementation of a unary fold. section 9.3.1

How Learn C++ by Example covers it

How deep it goes
Explains syntax, associativity, empty-pack failure, binary alternatives, and type requirements without exploring advanced fold patterns.
Examples
Uses an add function, integer assertions, subtraction associativity, empty calls, and concatenated strings.
What you can do after
Apply it via C++ variadic functions to reduce nonempty parameter packs with a chosen operator.
How it connects
Links parameter packs, variadic templates, operator overloading, concepts, and binary folds.

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.