5.2.16 · D3C++ Programming

Worked examples — Variadic templates — parameter packs, fold expressions

2,423 words11 min readBack to topic

The scenario matrix

Every variadic problem falls into one of these cells. We will cover all of them.

Cell What makes it different Danger if ignored
A. Associative op, non-empty +, *, && — direction of fold doesn't change the value none, but still pick a fold
B. Non-associative op -, /, string-build — left vs right give different answers wrong result silently
C. Empty pack, safe op &&, ||, , have identities fine
D. Empty pack, unsafe op +, * over empty → compile error code won't build
E. Single-element pack pack of size 1 — the "base of the fold" off-by-one confusion
F. Mixed types int, double, const char* together wrong common type
G. Side-effect / ordering comma fold, print-each evaluation order surprises
H. Compile-time count sizeof..., constexpr runtime vs compile-time mix-up
I. Word problem real task (invoice total, logging) translating words → fold
J. Exam twist fold-of-a-pattern, forwarding, index tricks subtle expansion rules

Below: 9 worked examples, each tagged with the cell(s) it covers.


Example 1 — Cell A: associative fold, direction doesn't matter


Example 2 — Cell B: non-associative op, direction changes the answer

Figure — Variadic templates — parameter packs, fold expressions

Example 3 — Cell C: empty pack, safe operators


Example 4 — Cell D & the fix: empty pack over an unsafe op


Example 5 — Cell E: the single-element pack (edge of the fold)


Example 6 — Cell F: mixed types and the common type


Example 7 — Cell G: side-effects and evaluation order (comma fold)


Example 8 — Cell H & I: compile-time count in a word problem


Example 9 — Cell J: exam twist — fold of a pattern, not a bare pack

Figure — Variadic templates — parameter packs, fold expressions

Recall Self-test before you close

Which fold direction gives ordinary human subtraction 10 - 3 - 2? ::: The left fold (... - xs) = ((10-3)-2) = 5. sum() with an empty pack and (xs + ...) — what happens? ::: Compile error (no + identity for empty pack). What does sum_sq(1,2,3) return and why not 36? ::: 14; the pattern xs*xs squares each element, not the total. avg(2.0,4.0,9.0) result? ::: 5.0 — sum 15 over count sizeof... = 3.

See also: Function Templates, Recursion, std::tuple, Perfect Forwarding, Operator Overloading.