The classic example for C++17 fold expressions is printing all arguments:
template<typename ... Args>
void print(Args ... args)
{
(cout << ... << args);
}
Example:
print("Hello", 12, 234.3, complex<float>{12.3f, 32.8f});
Output:
Hello12234.3(12.3,32.8)
I'd like to add newlines to my output. However, I can't find a good way to do that, the best I've found so far:
template<typename ... Args>
void print(Args ... args)
{
(cout << ... << ((std::ostringstream{} << args << "\n").str()));
}
This however isn't zero-overhead, as it constructs a temporary ostringstream
for each argument.
The following versions don't work either:
(cout << ... << " " << args);
error: expression not permitted as operand of fold expression
And
(cout << ... << (" " << args));
error: invalid operands to binary expression
I understand why the last two versions don't work. Is there a more elegant solution to this problem, using fold expressions?