# Variadic templates and fold expressions

> A parameter pack stands for zero or more template or function arguments, and the only thing you can do with one is expand it, repeating a pattern once per element. C++17 fold expressions reduce a pack with an operator, replacing most of the recursion that C++11 variadic code needed.

- **Source:** C++ Atlas (https://cppatlas.com/topics/variadic-templates-and-fold-expressions)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.variadic] (https://eel.is/c++draft/temp.variadic), [expr.prim.fold] (https://eel.is/c++draft/expr.prim.fold), [expr.sizeof] (https://eel.is/c++draft/expr.sizeof), [temp.param] (https://eel.is/c++draft/temp.param), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [expr.comma] (https://eel.is/c++draft/expr.comma)
- **cppreference links:** [Parameter pack](https://en.cppreference.com/w/cpp/language/parameter_pack), [Fold expressions](https://en.cppreference.com/w/cpp/language/fold), [sizeof... operator](https://en.cppreference.com/w/cpp/language/sizeof...), [std::forward](https://en.cppreference.com/w/cpp/utility/forward)
- **Prerequisites:** template-argument-deduction, forwarding-references-and-perfect-forwarding

## The one idea

A **parameter pack** is a name that stands for a list of zero or more things: types, values, templates, or function parameters. You cannot index it, loop over it, or pass it around as a unit in C++23. The one operation is **pack expansion**: you write a pattern that mentions the pack, follow it with `...`, and the compiler stamps out one copy of the pattern per element, separated by commas. A **fold expression** is a second, C++17 form of expansion that joins the copies with a binary operator instead of commas.

Every rule in this topic is a refinement of that. The pattern decides what gets repeated, the context decides where repetition is allowed, and deduction decides how long the pack is.

> **Mental model.** `pattern...` is a compile-time copy-and-paste. `f(g(xs)...)` becomes `f(g(x1), g(x2), g(x3))`; the `...` applies to the whole pattern to its left, not just to the pack name.

## Four kinds of pack

A template parameter pack is declared with `...` before the name. It can be a type pack (`class... Ts`), a non-type pack (`int... Ns`, or `auto... Vs` since C++17), or a template template pack (`template<class> class... Ts`). A **function parameter pack** is a function parameter whose type contains a template parameter pack, as in `Ts... xs`; its type is itself a pack expansion. C++20 added init-capture packs in lambdas, `[...ys = xs]`.

`sizeof...(pack)` gives the number of elements as a constant expression of type `std::size_t`. It counts elements; it has nothing to do with `sizeof`.

```cpp
#include <tuple>

template<class... Ts> constexpr auto count = sizeof...(Ts);
static_assert(count<int, void, char[3]> == 3);  // void is fine: no object is formed
static_assert(count<> == 0);

template<int... Ns> constexpr int isum = (Ns + ... + 0);
static_assert(isum<1, 2, 3> == 6);

template<template<class> class... Ts> struct Apply {
  using type = std::tuple<Ts<int>...>;  // one specialization per template
};

template<class... Ts> auto capture(Ts... xs) {
  return [...ys = xs] { return (ys + ...); };  // C++20 init-capture pack
}
```

A primary class, variable or alias template may have at most one template parameter pack, and it must come last. Function templates are more relaxed: a pack may be followed by template parameters that can be deduced from the function parameters or that have defaults.

## Patterns and where they can expand

The pattern is everything that belongs to the `...`. It may be as simple as the pack name or an arbitrarily complex expression or type. Moving the `...` changes the meaning completely.

```cpp
int g(int x) { return x * 10; }
template<class... Ts> int f(Ts... xs) { return (0 + ... + xs); }

template<class... Ts> int per_element(Ts... xs) { return f(g(xs)...); }  // f(g(x1), g(x2))
template<class... Ts> int all_at_once(Ts... xs) { return g(f(xs...)); }  // g(f(x1, x2))
```

A pattern may name several packs. They are expanded in lockstep, so they must all have the same length, and the program is ill-formed if they do not.

```cpp
#include <utility>

template<class... Ts> struct List {};
template<class... Ts> struct Zip {
  template<class... Us> using with = List<std::pair<Ts, Us>...>;
};
// Zip<int, char>::with<long, bool> is List<pair<int, long>, pair<char, bool>>
// Zip<int, char>::with<long> is ill-formed: lengths 2 and 1
```

Expansion is allowed only in contexts that are themselves comma-separated lists: function call arguments, template argument lists, braced initializer lists, base class lists, member initializer lists, lambda capture lists, `using` declarations (since C++17), `alignas` and attribute lists, and fold expressions. A bare `xs...;` as a statement is not one of them, and neither is `std::printf("%d", xs);` without any `...`, which is rejected as an unexpanded pack.

```cpp
template<class... Fs> struct overloaded : Fs... {  // pack expansion in the base list
  using Fs::operator()...;                         // C++17 pack expansion in using
};
```

> **Pitfall.** `xs + 1...` does not compile. The preprocessor reads `1...` as a single preprocessing number, which is not a valid token. Write `(xs + 1)...` or put a space before the dots.

## Recursion, then folds

Before C++17, the standard way to process a pack was recursion: peel off the first element, handle it, and recurse on the rest, with a non-variadic overload as the base case. It works, but it instantiates one function per element and spreads the logic over several declarations. The other C++11 idiom was expansion into an array initializer, abusing the comma operator to run an expression per element in a guaranteed order.

```cpp
#include <cstdio>

void print_rec() { std::puts(""); }                        // base case
template<class T, class... Rest> void print_rec(T t, Rest... rest) {
  std::printf("%d", t);
  print_rec(rest...);                                      // one instantiation per length
}

template<class... Ts> void print_array(Ts... xs) {
  int dummy[] = {0, (std::printf("%d", xs), 0)...};        // C++11 trick
  (void)dummy;
}

template<class... Ts> void print_fold(Ts... xs) {
  (std::printf("%d", xs), ...);                            // C++17
}
```

C++17 also allows the recursion to live in one function: `if constexpr (sizeof...(rest) > 0)` guards the recursive call, so no separate base-case overload is needed, but there is still one instantiation per length. A fold does the same work in a single instantiation and a single expression, and it is the default choice whenever the per-element work fits in an expression.

## The four fold forms

A fold expression is always parenthesized and uses one of 32 binary operators. With a pack `E` holding `E1, E2, E3` and an initial value `I`:

| Form | Spelling | Expands to |
| --- | --- | --- |
| Unary right fold | `(E op ...)` | `E1 op (E2 op E3)` |
| Unary left fold | `(... op E)` | `(E1 op E2) op E3` |
| Binary right fold | `(E op ... op I)` | `E1 op (E2 op (E3 op I))` |
| Binary left fold | `(I op ... op E)` | `((I op E1) op E2) op E3` |

The side the dots are on is the side the parentheses pile up on. For associative operators it does not matter; for subtraction or division it decides the answer.

```cpp
template<class... Ts> int rsub(Ts... xs) { return (xs - ...); }  // 10 - (4 - 3) == 9
template<class... Ts> int lsub(Ts... xs) { return (... - xs); }  // (10 - 4) - 3 == 3
```

The operand of a fold must be a cast-expression, so `(xs * 2 + ...)` is ill-formed; write `((xs * 2) + ...)`. The binary forms exist mainly for an initial value and for streams, as in `(std::cout << ... << xs)`.

An empty pack is where the forms differ. A binary fold of an empty pack is just `I`. A unary fold of an empty pack is allowed for exactly three operators: `&&` gives `true`, `||` gives `false`, and the comma operator gives `void()`. Every other operator, including `+` and `*`, makes the instantiation ill-formed, because the identity values in the original proposal were removed before C++17 shipped.

```cpp
template<class... Ts> constexpr bool all(Ts... xs) { return (... && xs); }
template<class... Ts> constexpr auto sum(Ts... xs) { return (xs + ... + 0); }
static_assert(all() && sum() == 0);
// (xs + ...) with an empty pack: error, no fallback value for +
```

> **Standardese.** [temp.variadic] says that when a unary fold is instantiated with an empty pack, `&&` yields `true`, `||` yields `false`, the comma operator yields `void()`, and for any other operator the instantiation is ill-formed.

## Folding over the comma, and evaluation order

`(f(xs), ...)` is the idiomatic "do this for every element". The comma operator sequences its left operand before its right, and that holds however the expression is grouped, so both the right fold and the left fold call `f` on the elements from first to last. That is a guarantee.

Expanding into function arguments gives no such guarantee. In `sink(f(xs)...)`, the arguments are indeterminately sequenced, and implementations do differ in practice. Expansion into a braced initializer list, as in the array trick, is evaluated left to right.

```cpp
#include <cstdio>

template<class... Ts> void sink(Ts...) {}

template<class... Ts> void show(Ts... xs) {
  (std::printf("%d", xs), ...);            // guaranteed 123 for show(1, 2, 3)
  sink((std::printf("%d", xs), 0)...);     // order unspecified
}
```

If the pattern's type might overload the comma operator, cast to `void`: `(void(f(xs)), ...)`. Overloaded commas are rare, but generic code that calls user functions is exactly where they show up.

## Packs and deduction

A function parameter pack at the end of the parameter list deduces one element per remaining argument, and its length is whatever is left. A function parameter pack anywhere else is a non-deduced context: it is never deduced from the call. Its elements must be given explicitly, and if it is the last template parameter and nothing is given, it is empty.

```cpp
template<class... Ts, class U> int last(Ts..., U u) { return u; }

int ok = last<int, int>(1, 2, 3);  // Ts = {int, int} explicitly, U = int deduced
// int no = last(1, 2, 3);         // error: Ts cannot be deduced from the call
```

Explicit arguments for a pack can also be extended by deduction: `f<int>(1, 2.0)` with `template<class... Ts> void f(Ts...)` gives `Ts = {int, double}`. Class template partial specializations use packs in the arguments, as in `template<class T, class... Rest> struct Count<T, Rest...>`, matching any non-empty list.

The most common pack in real code is a pack of forwarding references, `Args&&... args`, expanded as `std::forward<Args>(args)...`. Each element deduces independently, so one call can mix lvalues and rvalues, and the pattern `std::forward<Args>(args)` expands both packs in lockstep. Why that preserves value categories is the subject of the topic on forwarding references and perfect forwarding. C++26 pack indexing, `Ts...[0]`, has its own topic too.

## What to remember

- A pack can only be expanded; `pattern...` repeats the whole pattern once per element.
- Packs come as type, non-type, template template and function parameter packs, plus C++20 init-capture packs; `sizeof...` counts elements.
- Packs in one pattern expand in lockstep and must have equal lengths.
- Expansion is allowed only in list contexts and folds; `xs + 1...` fails to lex, so parenthesize.
- Unary folds group toward the dots; binary folds add an initial value used for empty packs.
- An empty unary fold is valid only for `&&` (true), `||` (false) and comma (`void()`).
- A comma fold evaluates left to right; expansion into function arguments does not guarantee order.
- Only a trailing function parameter pack is deduced from a call.

## Concept Map Outline

- **Variadic templates and folds:** A pack stands for zero or more arguments and can only be expanded.
  - **Kinds of pack:** Packs exist at every level a template can be parameterized.
    - **Template packs:** Type, non-type and template template packs: class... Ts, int... Ns.
    - **Function parameter packs:** Ts... xs; C++20 lambdas add init-capture packs [...ys = xs].
    - **sizeof...:** Counts elements as a std::size_t constant; unrelated to object sizes.
  - **Pack expansion:** pattern... repeats the whole pattern once per element.
    - **Pattern placement:** f(g(xs)...) calls g per element; g(f(xs...)) calls g once.
    - **Lockstep packs:** Several packs in one pattern must have the same length.
    - **List contexts only:** Arguments, initializers, bases, captures, using-declarations and folds.
    - **xs + 1...:** 1... lexes as one pp-number; write (xs + 1)... instead.
  - **Fold forms:** C++17 reduces a pack with one of 32 binary operators.
    - **Unary right:** (E op ...) groups as E1 op (E2 op E3).
    - **Unary left:** (... op E) groups as (E1 op E2) op E3.
    - **Binary folds:** (E op ... op I) and (I op ... op E) add an initial value.
    - **Operand restriction:** The operand is a cast-expression: parenthesize xs * 2 inside a fold.
  - **Empty packs:** Only three unary folds have a value for zero elements.
    - **&& and ||:** An empty && fold is true and an empty || fold is false.
    - **Comma:** An empty comma fold is void().
    - **Everything else:** Empty unary + or * is ill-formed; use a binary fold with an identity.
  - **Evaluation order:** Which expansions run their elements first to last.
    - **Comma fold:** (f(xs), ...) is sequenced left to right, in either fold direction.
    - **Call arguments:** sink(f(xs)...) evaluates the elements in unspecified order.
    - **Overloaded comma:** Cast to void, (void(f(xs)), ...), to bypass a user operator comma.
  - **Packs and deduction:** How a pack gets its length.
    - **Trailing pack:** A last function parameter pack deduces one element per remaining argument.
    - **Non-trailing pack:** Never deduced from the call; supply it explicitly.
    - **Forwarding packs:** Args&&... args with std::forward<Args>(args)... keeps each category.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.sizeof], [temp.variadic])

What is the value of `n`?

```cpp
template<class... Ts> constexpr auto count = sizeof...(Ts);

constexpr auto n = count<int, void, char[3]>;
```

A. 3
B. 8, the sum of the sizes on a typical 64-bit platform
C. Ill-formed: `void` cannot appear in a type pack
D. Ill-formed: `sizeof` cannot be applied to `void`

**Answer (A):** 3

**Why:** `sizeof...` counts the elements of a pack; it does not measure any type, so `void` and an array type are as good as any other element. The result is a `std::size_t` constant equal to 3. The size-related options confuse it with `sizeof`, which would indeed reject `void`.

### Question 2 [warmup] ([expr.prim.fold], [temp.variadic])

What does this program print?

```cpp
#include <cstdio>

template<class... Ts> int r(Ts... xs) { return (xs - ...); }
template<class... Ts> int l(Ts... xs) { return (... - xs); }

int main() { std::printf("%d %d\n", r(10, 4, 3), l(10, 4, 3)); }
```

A. `3 3`
B. `3 9`
C. `9 3`
D. `9 9`

**Answer (C):** `9 3`

**Why:** A unary right fold `(xs - ...)` groups toward the right: `10 - (4 - 3)`, which is 9. A unary left fold `(... - xs)` groups toward the left: `(10 - 4) - 3`, which is 3. The parentheses pile up on the side where the dots are. For an associative operator such as `+` both forms agree, which is why it is easy to forget that the choice matters.

### Question 3 [warmup] ([temp.variadic], [expr.prim.fold])

Is this program well-formed, and if so what does it return?

```cpp
template<class... Ts> int sum(Ts... xs) { return (xs + ...); }

int main() { return sum(); }
```

A. Well-formed; returns 0, the identity for `+`
B. Ill-formed: a unary fold over `+` with an empty pack has no value
C. Well-formed; returns an indeterminate value
D. Undefined behavior

**Answer (B):** Ill-formed: a unary fold over `+` with an empty pack has no value

**Why:** For an empty pack, a unary fold is defined only for `&&` (giving `true`), `||` (giving `false`) and the comma operator (giving `void()`). For `+` the instantiation is ill-formed, so `sum()` fails to compile. The identity value 0 was in the original fold-expression proposal but was removed before C++17. Write the binary fold `(xs + ... + 0)` to get 0 for an empty pack.

### Question 4 [tricky] ([expr.comma], [expr.call], [temp.variadic])

For the call `show(1, 2, 3)`, what does the standard guarantee about the output of lines #1 and #2?

```cpp
#include <cstdio>

template<class... Ts> void sink(Ts...) {}

template<class... Ts> void show(Ts... xs) {
  (std::printf("%d", xs), ...);         // #1
  sink((std::printf("%d", xs), 0)...);  // #2
}
```

A. Both print `123`
B. #1 prints `321`, because a right fold evaluates from the right; #2 is unspecified
C. #1 prints `123`; the order of #2 is unspecified
D. The order of both is unspecified

**Answer (C):** #1 prints `123`; the order of #2 is unspecified

**Why:** #1 expands to `printf(1), (printf(2), printf(3))`. The built-in comma operator sequences its left operand before its right however the operands are grouped, so the output is `123`. #2 expands into function arguments, which are indeterminately sequenced with respect to each other, so any order is permitted. The "right fold evaluates from the right" answer confuses grouping with evaluation order.

### Question 5 [tricky] ([lex.ppnumber], [temp.variadic])

Is the definition of `plus1` well-formed?

```cpp
#include <tuple>

template<class... Ts> auto plus1(Ts... xs) {
  return std::make_tuple(xs + 1...);
}
```

A. Yes: it expands to `make_tuple(x1 + 1, x2 + 1, ...)`
B. Yes, but it expands to `make_tuple(xs + 1, xs + 1, ...)` with the pack unexpanded
C. No: `1...` is lexed as a single preprocessing number, so the pack is never expanded
D. No: a pack expansion pattern cannot contain a literal

**Answer (C):** No: `1...` is lexed as a single preprocessing number, so the pack is never expanded

**Why:** Maximal munch in preprocessing turns `1...` into one pp-number, which cannot be converted to a valid token, so the code is ill-formed before templates are even considered; GCC reports too many decimal points. Patterns may contain literals freely, so writing `(xs + 1)...` or `xs + 1 ...` with a space gives the intended expansion of the first option.

### Question 6 [tricky] ([temp.deduct.call], [temp.deduct.type], [temp.param])

Which of the two calls is well-formed?

```cpp
template<class... Ts, class U> int last(Ts..., U u) { return u; }

int a = last<int, int>(1, 2, 3);  // #1
int b = last(1, 2, 3);            // #2
```

A. Both: `Ts` is deduced as `{int, int}` in #2
B. Only #2
C. Neither: a pack cannot be followed by another function parameter
D. Only #1

**Answer (D):** Only #1

**Why:** A function parameter pack that is not at the end of the parameter list is a non-deduced context, so `Ts` is never deduced from the call. In #1 `Ts` is given explicitly as `{int, int}`, the first two arguments match the pack, and `U` is deduced as `int` from the third. In #2 nothing supplies `Ts`, so deduction fails and #2 is ill-formed. The declaration itself is fine, because `U` can be deduced, which rules out the third option.

### Question 7 [standardese] ([temp.variadic], [stmt.return])

Each function is called with an empty pack in `main`. Which one makes the program ill-formed?

```cpp
template<class... Ts> bool a(Ts... xs) { return (... && xs); }
template<class... Ts> bool b(Ts... xs) { return (xs || ...); }
template<class... Ts> void c(Ts... xs) { return (xs, ...); }
template<class... Ts> int  d(Ts... xs) { return (xs * ...); }

int main() { a(); b(); c(); return d(); }
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (D):** `d`

**Why:** [temp.variadic] gives values for exactly three empty unary folds: `&&` is `true`, `||` is `false` and the comma operator is `void()`, which is why `c` may `return` it from a `void` function. Any other operator, including `*`, has no fallback and the instantiation is ill-formed. The tempting choice is `c`, since returning an expression from a `void` function looks wrong, but returning a `void` expression is allowed.

### Question 8 [standardese] ([temp.variadic])

What does the alias `Z` denote?

```cpp
#include <utility>

template<class... Ts> struct List {};

template<class... Ts> struct Zip {
  template<class... Us> using with = List<std::pair<Ts, Us>...>;
};

using Z = Zip<int, char>::with<long>;
```

A. `List<std::pair<int, long>>`; the shorter pack decides the length
B. Ill-formed: the packs expanded by one pattern must have the same length
C. `List<std::pair<int, long>, std::pair<char, long>>`
D. `List<std::pair<int, long>, std::pair<char, void>>`

**Answer (B):** Ill-formed: the packs expanded by one pattern must have the same length

**Why:** The pattern `std::pair<Ts, Us>` names two packs, so they expand in lockstep, and [temp.variadic] requires every pack in one expansion to have the same number of elements. With two `Ts` and one `Us` the alias is ill-formed; GCC reports mismatched argument pack lengths. There is no truncation or padding. `Zip<int, char>::with<long, bool>` would be `List<std::pair<int, long>, std::pair<char, bool>>`.
