9

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?

Update:

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

Amin Roosta
  • 1,080
  • 1
  • 11
  • 26
  • That's not what fold expressions are for. – Nicol Bolas Feb 13 '18 at 06:37
  • OK, here is the formal question: how to add arbitrary new items in the middle of a function parameter pack? – Amin Roosta Feb 13 '18 at 06:39
  • That's not what function parameter packs are for ;) I'm kidding, but I am being somewhat serious. Parameter packs are very specific tools for very specific jobs, and unpacking them is quite restricted. When they're exactly what you need, they work great, leading to clean and easily understood code. When they're nothing like what you need, you wouldn't use them. But when they're *almost* what you need, they're *annoyingly unusable*. – Nicol Bolas Feb 13 '18 at 06:40
  • You are right, It makes sense. The definition is "A function parameter pack is a function parameter that accepts zero or more function arguments." We can not add something in the middle of function arguments. – Amin Roosta Feb 13 '18 at 07:20

1 Answers1

17

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.

T.C.
  • 133,968
  • 17
  • 288
  • 421