Search code examples
c++stlc++14variadic-templatesostream

Sending a template parameter pack to std::basic_ostream


There's a code example on a cppreference page for std::integer_sequence:

template<typename T, T... ints>
void print_sequence(std::integer_sequence<T, ints...> int_seq)
{
    std::cout << "The sequence of size " << int_seq.size() << ": ";
    ((std::cout << ints << ' '),...);
    std::cout << '\n';
}

I don't quite understand the ((std::cout << ints << ' '),...) syntax. I don't see any overloaded versions of std::basic_ostream::operator<<` that would take a variadic template's parameter pack in.

What exactly is happening here, and how does it work?


Solution

  • I don't quite understand the ((std::cout << ints << ' '),...) syntax. I don't see any overloaded versions of std::basic_ostream::operator<< that would take a variadic template's parameter pack in.

    What exactly is happening here, and how does it work?

    If I'm not wrong, it's called "fold expression" but you can find it also as "template folding" or simply "folding".

    It's available starting from C++17.

    The idea is apply an operator over a variadic pack of values.

    Classic example: the sum.

    If you want the sum of your ints, you can apply the + operator as follows

    ( ints + ... );
    

    In your case, the fold expression is applied over the comma operator.

    So, if ints... is (for example) 2, 3, 5, 7, your expression:

    ((std::cout << ints << ' '),...);
    

    is equivalent to

    (std::cout << 2 << ' '), (std::cout << 3 << ' '), (std::cout << 5 << ' '), (std::cout << 7 << ' ');