Fold expressions
- C++ course
- Advanced
- Lesson 9/83
- 5 min
Learn pack processing with C++17 fold expressions.
Fold expressions
A fold expression (C++17) reduces a parameter pack with a single operator. Right fold: (args + ...). Left fold: (... + args). Each pack element is placed on the left and right of the operator.
Example: (args + ...) with args = {1, 2, 3, 4} computes 1 + (2 + (3 + 4)); the result is 10. Fold is much shorter than a recursive template. An empty pack errors; in that case an initial value (init) is required.
Fold with init value
An empty pack errors in a fold. To avoid this, use an initial value (init): (args + ... + 0). Even when the pack is empty the result is 0. This is useful for templates that compute sums or products.
Example: sum_all() should return 0 for an empty pack. (args + ... + 0) guarantees this. For products write (args * ... * 1); an empty pack yields 1. For logical AND use (args && ...).
Practice sum_all with fold
Write template <typename... Args> auto sum_all(Args... args). The body should be return (args + ...);. In main call sum_all(1, 2, 3, 4) and print the result via std::cout.
Starter code
#include <iostream>
// Write the sum_all template with a fold
int main() {
// Call sum_all(1, 2, 3, 4) and print
return 0;
}Sample solution
#include <iostream>
template <typename... Args>
auto sum_all(Args... args) {
return (args + ...);
}
int main() {
std::cout << sum_all(1, 2, 3, 4);
return 0;
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of fold is (args + ...)?
- Left fold
- Binary fold
- Right fold Correct answer
- Cross fold
Explanation: (args + ...) is a right fold; the pack is on the left.
2 Match the fold form
| Term | Meaning |
|---|---|
(args + ...) |
Right fold |
(... + args) |
Left fold |
(args + ... + 0) |
Right fold, with init |
(... + args + 0) |
Left fold, with init |
3 Complete the fold expression
template <typename... Args>
auto sum_all(Args... args) {
return (args + ____);
}
template <typename... Args>
auto sum_all(Args... args) {
return (args + ...);
}
Explanation: (args + ...) is a right fold.