5.2.16 · D3 · HinglishC++ Programming

Worked examplesVariadic templates — parameter packs, fold expressions

2,587 words12 min read↑ Read in English

5.2.16 · D3 · Coding › C++ Programming › Variadic templates — parameter packs, fold expressions


Scenario matrix

Har variadic problem in cells mein se kisi ek mein aata hai. Hum sab cover karenge.

Cell Kya cheez isse different banati hai Danger agar ignore karo
A. Associative op, non-empty +, *, && — fold ki direction value nahi badlti kuch nahi, phir bhi ek fold pick karo
B. Non-associative op -, /, string-build — left vs right alag answers dete hain galat result silently
C. Empty pack, safe op &&, ||, , ke identities hain theek hai
D. Empty pack, unsafe op +, * empty par → compile error code build nahi hoga
E. Single-element pack size 1 ka pack — "base of the fold" off-by-one confusion
F. Mixed types int, double, const char* saath mein galat 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) words → fold translate karna
J. Exam twist fold-of-a-pattern, forwarding, index tricks subtle expansion rules

Neeche: 9 worked examples, har ek cell(s) ke saath tagged.


Example 1 — Cell A: associative fold, direction matter nahi karta


Example 2 — Cell B: non-associative op, direction answer badal deta hai

Figure — Variadic templates — parameter packs, fold expressions

Example 3 — Cell C: empty pack, safe operators


Example 4 — Cell D aur fix: unsafe op par empty pack


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


Example 6 — Cell F: mixed types aur common type


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


Example 8 — Cell H & I: compile-time count ek word problem mein


Example 9 — Cell J: exam twist — bare pack nahi, ek pattern ka fold

Figure — Variadic templates — parameter packs, fold expressions

Recall Close karne se pehle self-test

Ordinary human subtraction 10 - 3 - 2 kaun si fold direction deti hai? ::: Left fold (... - xs) = ((10-3)-2) = 5. sum() empty pack ke saath aur (xs + ...) — kya hota hai? ::: Compile error (empty pack ke liye koi + identity nahi). sum_sq(1,2,3) kya return karta hai aur 36 kyun nahi? ::: 14; pattern xs*xs har element ko square karta hai, total ko nahi. avg(2.0,4.0,9.0) ka result? ::: 5.0 — sum 15 over count sizeof... = 3.

Dekho bhi: Function Templates, Recursion, std::tuple, Perfect Forwarding, Operator Overloading.