Fold expression not working (beginner example)

Hi,
Wondering why this fold expression does not work (args is a parameter pack):

 
  (cout << ... << (args << std::endl));


Following binary left fold:
( init op ... op pack )
If you wrote this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using std::cout;

template<typename ... Args>
void foo(Args ... args)
{
	(cout << ... << (args << std::endl));
}

int main()
{
	foo("abc", 123);
}

The foo function that gets instantiated and called here would be equivalent to:
1
2
3
4
void foo(const char* arg1, int arg2)
{
	cout << (arg1 << std::endl) << (arg2 << std::endl);
}

As you can see, this is not what you wanted, right?

What I think you probably want is the following:
 
(cout << ... << args) << std::endl;

Last edited on
Alternatively:
((std::cout << args << std::endl), ...);
With the caveat that this could call an overloaded comma if one is available for the expression (std::cout << args << std::endl)

If the code is supposed to be very generic it might be necessary to convert the expression to void, to use the built-in comma only:
(void(std::cout << args << std::endl), ...);
Last edited on
Note that there is a difference between mbozzi's and my suggested code.

foo("abc", 123) would print ...

with my version:
abc123

with mbozzi's version:
abc
123
Last edited on
Topic archived. No new replies allowed.