skip to content

Parameter Packs and Folds

A parameter pack takes any number of arguments, expands with ..., and a C++17 fold expression reduces it with one operator. Interviewers ask how printf-style helpers are written.

on this pageshow

explore

questions

5

How do you sum a C++ parameter pack with a C++17 fold expression, and what happens when the pack is empty?

level: middleimportance: must knowfreq 65%

answer

  1. parentheses, operator, ellipsis
  2. unary or binary, left or right
  3. an init value for the empty case
  4. only &&, || and comma have defaults

basics

~20 s

Write (xs + ...) for a unary fold, or (xs + ... + 0) for a binary fold with an initial value. A unary + fold over an empty pack is ill-formed; only &&, || and comma have empty-pack values: true, false, void().

solid answer

~50 s

A **fold expression** (C++17) reduces a pack with one binary operator and must be parenthesized. `(xs + ...)` is a **unary right fold**, expanding to `x1 + (x2 + x3)`; `(... + xs)` is a **unary left fold**, `(x1 + x2) + x3`. A **binary fold** adds an initial value: `(xs + ... + 0)` or `(0 + ... + xs)`. The empty pack is the trap: a unary fold over an empty pack is ill-formed for every operator except `&&` (yields `true`), `||` (yields `false`) and `,` (yields `void()`). Clang reports `unary fold expression has empty expansion for operator '+' with no fallback value`. So a `sum()` that may be called with no arguments needs the binary form. Direction matters for non-associative operators: with `10, 3, 2`, `(... - xs)` gives 5 and `(xs - ...)` gives 9. Thirty-two binary operators are allowed, including comparisons, assignments, `.*` and `->*`.

code

cpp · 15 lines
cpp
#include <cstdio>

template <typename... Ts> auto sum_unary(Ts... xs) { return (xs + ...); }      // unary right fold
template <typename... Ts> auto sum_binary(Ts... xs) { return (xs + ... + 0); } // binary right fold, init 0
template <typename... Ts> auto sub_left(Ts... xs) { return (... - xs); }       // ((x1 - x2) - x3)
template <typename... Ts> auto sub_right(Ts... xs) { return (xs - ...); }      // (x1 - (x2 - x3))
template <typename... Ts> bool all_ok(Ts... xs) { return (... && xs); }        // empty pack: true

int main() {
    std::printf("%d\n", sum_unary(1, 2, 3));        // 6
    std::printf("%d\n", sum_binary());              // 0: the init value
    std::printf("%d %d\n", sub_left(10, 3, 2), sub_right(10, 3, 2));  // 5 9
    std::printf("%d %d\n", all_ok(), all_ok(true, false));            // 1 0
    // sum_unary();  // error: unary fold expression has empty expansion for operator '+' with no fallback value
}

go deeper

for a junior

Know that C++17 lets you write (xs + ...) to add all elements of a pack instead of writing recursion.

for a middle

Name the four forms, give the empty-pack values of &&, || and comma, and use a binary fold with an identity element when no arguments are possible.

for a senior

Explain when direction changes the result, why stream output needs a binary left fold, and why comparison folds do not test ordering.

for a principal

Prefer folds over recursive helpers in shared code for compile time and readability, and make empty-pack behaviour an explicit part of each variadic API.

## The four forms A **fold expression**, added in C++17, applies one binary operator across all elements of a pack. The grammar requires the surrounding parentheses, and the position of the ellipsis decides the shape: | Form | Syntax | Expands to (3 elements) | |---|---|---| | Unary right fold | `(xs op ...)` | `x1 op (x2 op x3)` | | Unary left fold | `(... op xs)` | `(x1 op x2) op x3` | | Binary right fold | `(xs op ... op init)` | `x1 op (x2 op (x3 op init))` | | Binary left fold | `(init op ... op xs)` | `((init op x1) op x2) op x3` | `xs` can be any expression containing an unexpanded pack, so `(scale(xs) + ...)` folds over the scaled values. In a binary fold, exactly one of the two operands contains the pack, and both operators must be the same. ## Summing a pack ```cpp template <typename... Ts> auto sum_unary(Ts... xs) { return (xs + ...); } template <typename... Ts> auto sum_binary(Ts... xs) { return (xs + ... + 0); } ``` `sum_unary(1, 2, 3)` and `sum_binary(1, 2, 3)` both return 6. The difference appears only with no arguments. ## The empty pack When the pack is empty, a unary fold has no operands. The standard defines a value for only three operators: - `&&` gives `true`, so `(... && checks)` over nothing is "all of nothing passed". - `||` gives `false`. - `,` gives `void()`. For every other operator, a unary fold over an empty pack is **ill-formed**. Calling `sum_unary()` fails to compile; Clang 21 says: ```plaintext error: unary fold expression has empty expansion for operator '+' with no fallback value ``` The binary form supplies the fallback: `sum_binary()` returns the initial value, 0. The initial value should be the operator's identity element — `0` for `+`, `1` for `*` — or the result changes for non-empty packs too. The type matters as well: with `(xs + ... + 0)` the init is an `int`, so a pack of `double`s still produces a `double` through the usual arithmetic conversions, but a pack of `std::string`s cannot add `0`; use `std::string{}` as the init there. ## Left versus right For associative operators the direction changes only the evaluation shape. For others it changes the answer: ```cpp template <typename... Ts> auto sub_left(Ts... xs) { return (... - xs); } // (10 - 3) - 2 = 5 template <typename... Ts> auto sub_right(Ts... xs) { return (xs - ...); } // 10 - (3 - 2) = 9 ``` It can also matter for types: `(std::cout << ... << args)` must be a binary **left** fold, because each `<<` returns the stream that the next one writes to. Written as a right fold, it would try to shift the arguments into each other. ## The operators allowed Thirty-two binary operators may appear in a fold: - arithmetic and bitwise: `+ - * / % ^ & | << >>` - compound and plain assignment: `+= -= *= /= %= ^= &= |= <<= >>= =` - comparison and logical: `== != < > <= >= && ||` - the comma operator, and the pointer-to-member operators `.*` and `->*` A fold works on whatever those operators do for the element types, including user-defined overloads. Comparison folds rarely do what people expect: `(xs < ...)` builds `x1 < (x2 < x3)`, comparing a value with a `bool`, not checking that the pack is sorted. ## Folds versus recursion Before C++17, the same sum needed a recursive template with a base-case overload, instantiating one function per pack length. A fold is a single expression in a single instantiation, so it compiles faster and reads closer to the intent. Recursion remains useful when each step needs a different action than one operator can express. A middle path is a fold over the comma operator that calls a lambda per element, which keeps one instantiation while allowing several statements per element. ## Why interviewers ask "Write a variadic sum" is a standard middle-level exercise. The fold itself is one line; the follow-up — what happens with no arguments — checks whether the candidate knows the empty-pack rule and the binary form.

  • How do you check in one expression that every field of a pack passed validation?
    Use a fold over `&&`: `return (... && is_valid(fields));`. With built-in `bool` operands it short-circuits, stopping at the first `false`, and an empty pack yields `true` because `&&` has a defined empty-pack value. The `||` fold is the any-of counterpart and yields `false` for an empty pack.
  • Why must a stream-printing fold be written (std::cout << ... << args)?
    Each `<<` returns the stream, and the next insertion must apply to that stream, so the expression must group as `((std::cout << a0) << a1) << a2`. That is a binary left fold with `std::cout` as the initial value. A right fold would group the arguments first and try to shift them into one another.

  • A unary + fold over an empty pack evaluates to 0.
  • Fold expressions do not need parentheses around them.
  • Left and right folds always give the same result.
  • Any value works as the initial value of a binary fold.
  • (xs < ...) checks that the pack is in ascending order.
open as a page

In C++, what do typename... Ts and Ts... args declare in a variadic log_event template, and what does sizeof...(Ts) return?

level: juniorimportance: should knowfreq 60%

basics

~20 s

typename... Ts declares a template parameter pack of zero or more types; Ts... args declares a function parameter pack with one parameter per type. sizeof...(Ts) is the number of elements in the pack, a compile-time std::size_t, not a size in bytes.

open as a page

In C++, what is the difference between total(square(xs)...) and square(total(xs...)), and where else can a pack expansion appear?

level: middleimportance: should knowfreq 45%

basics

~20 s

The ellipsis repeats the whole pattern to its left. total(square(xs)...) squares each element and passes the results to total; square(total(xs...)) passes every element to one total call. Expansions also appear in base lists, member initializers and braced initializers.

open as a page

Your C++ telemetry logger prints its arguments by recursion over a parameter pack; why rewrite it as a comma fold, and why not expand into function arguments instead?

level: seniorimportance: should knowfreq 45%

basics

~10 s

Recursion instantiates one function per remaining pack length and needs a base case; a comma fold, (static_cast<void>(emit(args)), ...), is one expression evaluated left to right. Expanding into function arguments, sink(emit(args)...), leaves the order unspecified.

open as a page

How does C++26 pack indexing with Ts...[I] and values...[I] replace the older ways of reaching the Nth element of a pack?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

C++26 lets you subscript a pack: Ts...[I] names the Ith type and values...[I] the Ith value, with I a constant expression below sizeof.... Earlier code needed recursive helper templates or std::tuple_element_t and std::get on a tuple.

open as a page