skip to content

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%

answer

  1. one instantiation per pack length
  2. the comma operator sequences left to right
  3. function arguments are indeterminately sequenced
  4. cast to void against operator,

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.

solid answer

~50 s

The pre-C++17 logger peels one argument per call: `log_rec(T first, Rest... rest)` emits `first` and calls `log_rec(rest...)`, with a non-template `log_rec()` ending the recursion. Three arguments instantiate three function templates of decreasing length, each a real call unless inlined, and the base-case overload must be declared first. A C++17 **comma fold**, `(static_cast<void>(emit(args)), ...);`, is one expression in one function. The built-in comma operator evaluates its left operand before its right, so the output is in argument order. Expanding into a call, `sink(emit(args)...)`, is not equivalent: the initializations of function parameters are indeterminately sequenced, so the order is unspecified — Apple clang happened to print in order, but code must not rely on it. The `static_cast<void>` guards against a user-defined `operator,` for `emit`'s return type, which would otherwise be called by the fold. Before C++17, the order-safe trick was a braced list, `int order[] = {0, (emit(args), 0)...};`.

code

cpp · 32 lines
cpp
#include <cstdio>

int emit(int v) { std::printf("%d ", v); return v; }

// Pre-C++17: peel one argument per call; a base case ends the recursion
void log_rec() { std::printf("\n"); }
template <typename T, typename... Rest>
void log_rec(T first, Rest... rest) {          // instantiated once per remaining length
    emit(first);
    log_rec(rest...);
}

// C++17: one function, a comma fold sequenced left to right
template <typename... Ts>
void log_fold(Ts... args) {
    (static_cast<void>(emit(args)), ...);      // void cast: no user-defined operator, can hijack
    std::printf("\n");
}

// Pre-C++17 trick: braced-init-list elements are evaluated in order
template <typename... Ts>
void log_braced(Ts... args) {
    int order[] = {0, (emit(args), 0)...};     // leading 0 keeps the array non-empty
    (void)order;
    std::printf("\n");
}

int main() {
    log_rec(1, 2, 3);       // 1 2 3
    log_fold(1, 2, 3);      // 1 2 3
    log_braced(1, 2, 3);    // 1 2 3
}

go deeper

for a junior

Know that a pack can be processed either by a recursive template with a base case or, since C++17, by a fold expression in one function.

for a middle

Write both versions and explain why the recursive one needs a base-case overload declared first.

for a senior

Explain the sequencing guarantees of the comma operator and braced lists versus the unspecified order of function arguments, and guard folds against an overloaded comma.

for a principal

Set the variadic style for a shared library, folds with void casts by default, considering compile time, code size and how readable instantiation errors are.

## The recursive version Before C++17 there was no fold expression, so a variadic logger processed one argument per call: ```cpp void log_rec() { std::printf("\n"); } // base case template <typename T, typename... Rest> void log_rec(T first, Rest... rest) { emit(first); log_rec(rest...); // recurse on the tail } ``` For `log_rec(1, 2, 3)` the compiler instantiates `log_rec<int, int, int>`, `log_rec<int, int>` and `log_rec<int>`, then calls the non-template base case. The costs: - **One instantiation per length**, and per distinct combination of types. A logger called from hundreds of sites with different argument lists produces many small functions, which costs compile time and, without inlining, code size and call overhead. - **A base case is required**, and it must be declared before the recursive template so the call `log_rec(rest...)` with an empty pack can find it. - **Error messages nest**: a failure deep in the recursion prints one `in instantiation of` note per level. Recursion is still the right tool when each step must do something a single operator cannot express, such as treating the first argument as a format and the rest as values. ## The fold version C++17's fold over the comma operator applies an expression to every element in one function: ```cpp template <typename... Ts> void log_fold(Ts... args) { (static_cast<void>(emit(args)), ...); } ``` This is a unary right fold, expanding to `(e1, (e2, e3))`. The **built-in comma operator** evaluates its left operand completely before its right operand, so the elements are emitted in order: `1 2 3`. An empty pack is fine, because the comma fold over nothing yields `void()`. ## Why not expand into function arguments A tempting alternative is to expand into the arguments of a do-nothing function: ```cpp template <typename... Ts> void log_args(Ts... args) { sink(emit(args)...); } ``` It compiles, and on Apple clang 21 it printed `1 2 3`. But the standard says that the initialization of each function parameter, including its side effects, is **indeterminately sequenced** with respect to the others. The output order is unspecified, may differ between compilers and optimization levels, and a reviewer should reject it for any side effect whose order matters. ## The pre-C++17 ordering trick Code that must build as C++14 used a braced list, because the standard guarantees that the elements of a braced initializer list — including those produced by a pack expansion — are evaluated in the order they appear: ```cpp int order[] = {0, (emit(args), 0)...}; // leading 0 keeps the array non-empty ``` It works, but it reads as a hack, creates an unused array, and needs that extra `0` because a zero-length array is ill-formed. ## The overloaded comma trap A fold with `,` uses whatever comma operator the operand types select. If `emit` returns a class type for which someone defined `operator,`, the fold calls that function between elements: ```plaintext 1 2 3 <comma> <comma> ``` Under the C++23 wording an overloaded `operator,` still sequences its operands as the built-in one does, left to right, so the order survives, but extra user code runs and the result type changes. Casting each operand to `void` — `static_cast<void>(emit(args))` — makes the built-in comma the only candidate, because `void` cannot be an argument of a user-defined operator. Generic libraries write the cast as a matter of habit, because they cannot know which argument types callers will pass, and an `operator,` declared in some distant namespace is found by argument-dependent lookup. ## Comparison | Approach | Order guaranteed | Instantiations | Empty pack | Standard | |---|---|---|---|---| | Recursion with base case | yes | one per length | base case | C++11 | | Braced-list trick | yes | one | needs a leading element | C++11 | | Function-argument expansion | no | one | fine | C++11 | | Comma fold | yes | one | fine | C++17 | ## Why interviewers ask Rewriting a recursive variadic function as a fold is a common senior exercise. The strong answer goes beyond "folds are shorter": it explains sequencing — why the comma fold and braced lists are ordered and function arguments are not — and guards against an overloaded comma.

  • Why does the braced-list trick need the leading 0 in int order[] = {0, (emit(args), 0)...};?
    For an empty pack the expansion produces no elements, and `int order[] = {};` would declare an array of zero size, which is ill-formed. The leading `0` guarantees at least one element. The comma inside `(emit(args), 0)` discards `emit`'s result and supplies an `int` for each element, so `emit` may return anything, including `void`.
  • When is recursion still the better structure for a variadic logger?
    When the steps differ, such as consuming a format string piece by piece and matching each placeholder to the next argument, or when processing must stop early based on a value. Folds apply one operator uniformly; recursion, or a fold over a lambda that carries state, handles position-dependent logic. C++26 pack indexing also removes some recursion used only to reach the Nth element.

  • sink(emit(args)...) evaluates the arguments left to right by the standard.
  • A comma fold over an empty pack is ill-formed.
  • The recursive version instantiates only one function template.
  • An overloaded operator, cannot be called by a fold expression.
  • The static_cast<void> in the fold is only there to silence a warning.