In C++, what is the difference between total(square(xs)...) and square(total(xs...)), and where else can a pack expansion appear?
answer
- the ellipsis repeats what is to its left
- pattern contains the pack
- one call per element or one call
- bases, initializers, using-declarations
basics
~20 sThe 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.
solid answer
~40 sA **pack expansion** is a pattern followed by `...`; the compiler copies the pattern once per pack element. In `total(square(xs)...)` the pattern is `square(xs)`, so for `1, 2, 3` it becomes `total(square(1), square(2), square(3))` = 14. In `square(total(xs...))` the pattern is just `xs`, so it becomes `square(total(1, 2, 3))` = 36. Expansions are allowed only where the grammar takes a list: function arguments, braced initializers, template argument lists, **base class lists** (`struct Record : Field<Ts>...`), **member initializer lists** (`Field<Ts>(vs)...`), **using-declarations** (`using Fs::operator()...;`, C++17), lambda captures, `sizeof...` and fold expressions. When a pattern names two packs, they expand in lockstep and must have the same length; clang otherwise reports packs `that have different lengths`.
code
cpp · 27 lines#include <cstdio>
#include <string>
template <typename T> struct Field { // one column of a telemetry record
T value;
explicit Field(T v) : value(v) {}
};
template <typename... Ts>
struct Record : Field<Ts>... { // base list: Field<T0>, Field<T1>, ...
explicit Record(Ts... vs) : Field<Ts>(vs)... {} // mem-initializers: Ts and vs in lockstep
static constexpr std::size_t width = sizeof...(Ts);
};
int square(int x) { return x * x; }
int total(int a, int b, int c) { return a + b + c; }
template <typename... Ts> int per_element(Ts... xs) { return total(square(xs)...); } // square each
template <typename... Ts> int whole_pack(Ts... xs) { return square(total(xs...)); } // total gets all
int main() {
Record<int, double, std::string> r(7, 0.5, "eu-1");
std::printf("%zu %d %.1f %s\n", Record<int, double, std::string>::width,
static_cast<Field<int>&>(r).value, static_cast<Field<double>&>(r).value,
static_cast<Field<std::string>&>(r).value.c_str());
std::printf("%d %d\n", per_element(1, 2, 3), whole_pack(1, 2, 3)); // 14 36
}go deeper
Know that writing ... after something that mentions a pack repeats it for every element, and that the result is a comma-separated list.
Expand patterns on paper, distinguishing f(g(xs)...) from f(g(xs...)), and list the contexts where an expansion is allowed.
Use expansions in base lists and member initializers, keep lockstep packs the same length, and apply the C++17 using-declaration expansion for overload sets.
Judge when expansion-heavy designs such as inheriting from every element hurt error messages and compile time enough to justify simpler structures.
## The rule: the ellipsis repeats its pattern A **pack expansion** has two parts: a **pattern** that mentions at least one pack, and the `...` after it. When the template is instantiated, the compiler writes out the pattern once per element, substituting that element for the pack, and separates the copies with commas. Everything to the left of the ellipsis that belongs to the same syntactic unit is part of the pattern. That makes the ellipsis's position the whole story: | Expression | Pattern | For `xs = 1, 2, 3` | Result | |---|---|---|---| | `total(square(xs)...)` | `square(xs)` | `total(square(1), square(2), square(3))` | 14 | | `square(total(xs...))` | `xs` | `square(total(1, 2, 3))` | 36 | | `f(g(xs, n)...)` | `g(xs, n)` | `f(g(1, n), g(2, n), g(3, n))` | — | | `f(h(xs...)...)` | — | ill-formed: the inner expansion leaves nothing for the outer one | — | A pattern may also mention a non-pack name, such as `n` above, which is repeated unchanged in each copy. ## Where expansions may appear The standard lists the contexts; each needs a comma-separated list. The ones that matter in practice: - **Function call arguments**: `total(square(xs)...)`. - **Braced initializers**: `std::vector<std::string> fields{to_text(xs)...};`. - **Template argument lists**: `std::tuple<Ts*...>` or `Record<std::decay_t<Ts>...>`. - **Function parameter lists**: `Ts... args` itself is an expansion of the pattern `Ts`. - **Base class lists**: `struct Record : Field<Ts>... {}` inherits from one `Field` per type. - **Member initializer lists**: `Record(Ts... vs) : Field<Ts>(vs)... {}`. - **Using-declarations** (C++17): `using Fs::operator()...;`. - **Lambda captures**, **`sizeof...`**, **fold expressions**, attribute lists and `alignas`. A plain statement such as `print(xs)...;` is not one of them; that need is what the comma fold `(print(xs), ...);` covers. ## Record<Ts...>: expansion in bases and initializers A telemetry record holding one field per type uses two expansions that run in lockstep: ```cpp template <typename... Ts> struct Record : Field<Ts>... { explicit Record(Ts... vs) : Field<Ts>(vs)... {} }; ``` The pattern `Field<Ts>(vs)` names two packs, `Ts` and `vs`. They are expanded **together**, element by element, so the first base is initialized from the first value. Packs expanded together must have the same length; the compiler checks it and rejects a mismatch. In a class template where `Ts` comes from the class and `Us` from a member function, clang 21 reports: ```plaintext error: pack expansion contains parameter packs 'Ts' and 'Us' that have different lengths (2 vs. 3) ``` With distinct types each `Field<T>` base can be reached with `static_cast<Field<int>&>(r)`. If two types repeat, `Record<int, int>` does not even instantiate: clang reports `base class 'Field<int>' specified more than once as a direct base class` — one reason real tuple-like types tag each base with an index. ## The overload-set idiom C++17 allowed pack expansion in a using-declaration, which made this idiom possible: ```cpp template <typename... Fs> struct Overloaded : Fs... { using Fs::operator()...; }; template <typename... Fs> Overloaded(Fs...) -> Overloaded<Fs...>; ``` `Overloaded on{[](int i) { return i * 2; }, [](double d) { return d / 2; }};` inherits from both closure types and brings both call operators into one overload set, so `on(21)` returns 42 and `on(1.0)` returns 0.5. In C++14 mode clang warns that the using-declaration expansion is a C++17 extension, and the class template argument deduction the idiom also needs does not exist there. ## Reading an expansion A reliable way to read any expansion: 1. Find the `...`. 2. Walk left to the start of the expression, type or initializer it closes — stopping at the enclosing comma, opening parenthesis or angle bracket. 3. List the packs mentioned in that pattern; they must all have the same length. 4. Write the pattern out once per element, substituting element *i* of every pack in copy *i*. ## Common mistakes - Expanding too early or too late, as in the table above — read the pattern as "everything left of the dots, up to the enclosing comma or bracket". - Expecting `print(xs)...;` as a statement to work: it does not; use a fold. - Mixing packs of different lengths in one pattern. ## Why interviewers ask Placing the ellipsis correctly is the daily skill of variadic code. A candidate who can expand `square(xs)` versus `xs` on paper, and name the base-list and initializer contexts, can read and write the library code that uses them.
- What does std::tuple<Ts*...> become for Ts = int, double, and how does it differ from std::tuple<Ts...>*?The pattern of `Ts*...` is `Ts*`, so it becomes `std::tuple<int*, double*>`, a tuple of pointers. In `std::tuple<Ts...>*` the pattern is just `Ts`, giving `std::tuple<int, double>*`, a pointer to one tuple. Where the ellipsis sits relative to the `*` changes which entity is repeated.
- What goes wrong with Record<int, int> when Record inherits from Field<Ts>...?The base list expands to `Field<int>, Field<int>`, and a class may not name the same direct base twice, so the instantiation is ill-formed; clang reports the base class specified more than once as a direct base class. Tuple-like types avoid this by giving each base a distinct identity, for example an index parameter alongside the type, such as `Field<0, int>` and `Field<1, int>`.
- total(square(xs)...) and square(total(xs...)) always produce the same result.
- The ellipsis applies only to the name immediately before it.
- Two packs in one pattern may have different lengths; the shorter one repeats.
- print(xs)...; as a statement prints every element.
- Pack expansion is not allowed in a base class list.