C++ Fold Expressions Folding over a comma

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

It is a common operation to need to perform a particular function over each element in a parameter pack. With C++11, the best we can do is:

template <class... Ts>
void print_all(std::ostream& os, Ts const&... args) {
    using expander = int[];
    (void)expander{0,
        (void(os << args), 0)...
    };
}

But with a fold expression, the above simplifies nicely to:

template <class... Ts>
void print_all(std::ostream& os, Ts const&... args) {
    (void(os << args), ...);
}

No cryptic boilerplate required.



Got any C++ Question?