C/C++ Arena

Step 1 of 6

Parameter packs and fold expressions

A variadic template accepts any number of arguments, of any types, as a parameter pack:

template <typename... Ts>
auto sum(Ts... xs) {
    return (xs + ...);      // a fold expression: x1 + (x2 + (x3 + ...))
}
sum(1, 2, 3);        // 6
sum(1.5, 2);         // 3.5

sizeof...(xs) gives the number of arguments. Fold expressions work with any binary operator: (xs && ...), (... , f(xs)) and so on. std::make_unique, std::tuple, emplace_back and std::format are all built on packs.

Your turn: write count_if_all(pred, xs...), returning how many of the arguments satisfy pred, and all_positive(xs...). Use fold expressions, no loops.

Next: Perfect forwarding