Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Fold expression

A fold expression combines pack elements using a binary operator. Learn the four syntax forms, how fold direction controls grouping, and the empty-pack rules through a small summation example with an initial value.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

(... op pack)              // unary left fold
(pack op ...)              // unary right fold
(init op ... op pack)      // binary left fold
(pack op ... op init)      // binary right fold

A fold expression expands a pack and combines its elements using a binary operator. The enclosing parentheses are mandatory. In the syntax shown, both pack and init must match the cast-expression grammar rule: pack contains an unexpanded pack, and init does not. For example, 1 * 2 cannot be used as init without parentheses; write (1 * 2) instead. The placeholder op denotes a permitted operator, such as +, -, &&, ||, or ,. In a binary fold, both operators must be identical; exactly one side contains an unexpanded pack.

The unary forms are left (... op pack) and right (pack op ...); the binary forms are left (init op ... op pack) and right (pack op ... op init). “Unary” means there is no init, not that the operator is unary. Direction determines grouping: for a, b, c, a left fold with - gives ((a - b) - c), whereas a right fold gives (a - (b - c)). Do not equate grouping with operand evaluation order.

For an empty pack, a unary fold is valid only with && (result true), || (false), and , (void()). A binary fold then yields init. In the example, (0 + ... + values) is a binary left fold: for 1, 2, 3 it corresponds to (((0 + 1) + 2) + 3), and for an empty pack it yields 0. The initial value participates in operator and type selection; it is not merely an empty-pack fallback.

Examples

#include <iostream>

template<class... Ts>
constexpr auto sum(Ts... values) {
    return (0 + ... + values);
}

int main() {
    static_assert(sum() == 0);
    static_assert(sum(1, 2, 3) == 6);
    std::cout << sum(1, 2, 3) << '\n';
    std::cout << sum() << '\n';
}

Result

6
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources