cpp / expert
Snippet
Fold Expressions for Variadic Templates
Introduced in C++17, fold expressions simplify operations on variadic template parameter packs. Instead of recursive template calls, you can use a single expression to apply an operator across all elements in the pack.
snippet.cpp
1
2
3
4
5
6
7
template <typename... Args>auto sum(Args... args) {return (... + args);}// Usage:// int total = sum(1, 2, 3, 4, 5); // 15
Breakdown
1
typename... Args
Declares a parameter pack representing an arbitrary number of template arguments.
2
(... + args)
A unary right fold that expands to (arg1 + (arg2 + (arg3...))).