C++ · 4 · Templates & Generic Programming18 / 36 · 50%
Variadic Templates & Fold Expressions
Type-safe varargs — any number of arguments, any types.
Examples: typename... Args, sizeof...(), fold
shortcuts: ← prev · → next · M mark
1
Parameter Packs
Args... is a list of types; args... is a list of values.
Example
example
template <typename... Args>
void log(Args&&... args) {
std::cout << "arity=" << sizeof...(Args) << '\n';
}2
Fold Expressions (C++17)
Expand a pack over an operator in one expression.
Example
example
template <typename... Args>
auto sum(Args... args) { return (args + ... + 0); }
template <typename... Args>
void print(Args&&... args) { ((std::cout << args << ' '), ...); }
print("x", 1, 2.5); // x 1 2.53
Recursive Expansion
Pre-C++17 style, still useful when each element needs different handling.
Example
example
void print() { std::cout << '\n'; }
template <typename T, typename... Rest>
void print(const T& first, const Rest&... rest) {
std::cout << first << ' ';
print(rest...); // peel one argument per call
}4
Where You Meet Them
The standard library is built on packs.
Complexity
| std::make_unique<T>(args...) | forwarding pack | |
| emplace_back(args...) | in-place construction | |
| std::tuple<Ts...> | heterogeneous storage | |
| std::format(fmt, args...) | type-safe printf |