A unary fold combines every element in a parameter pack with an operator, without an explicit initial value. With +, (... + tail) expands a pack into a left-associative expression; (tail + ...) produces a right fold. section 9.3.1
Adding a parameter pack
template<typename... Ts> auto add(const Ts&... tail) { return (... + tail); } works for add(1, 2, 3) and add(1), but fails for add() because a unary fold over + requires a nonempty pack. Associativity matters for non-associative operators: subtraction gives different results on the left and right. section 9.3.1
Important constraints and alternatives:
- Use a binary fold when an empty pack must be supported, such as (0 + ... + tail). section 9.3.1
- Any operator that applies to the parameters can be used, including operator+ for strings. section 9.3.1
Listing 9.11 Fold example
template<typename... Ts> #1
auto add(const Ts&... tail) #2
{
return (... + tail); #3
}
View the compact C++ implementation of a unary fold. section 9.3.1
