c++c++17fold-expression

How to Insert spaces in (cout << ... << args) using fold expressions?


Given

template<typename ...Types>
void print(Types&& ...args) {
    (cout << ... << args);
}
// ....
print(1, 2, 3, 4); // prints 1234

How to add spaces so we get 1 2 3 4?


Solution

  • The usual workaround is to fold over the comma operator instead, though the simplistic approach will leave a trailing space:

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

    Changing it to avoid the trailing space is left as an exercise for the reader.