Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to insert extra operation in fold expression?

In C++17, fold expression is available, so to print arguments, we could use

#define EOL '\n'

template<typename ...Args>
void output_argus(Args&&... args) 
{
    (cout << ... << args) << EOL;
}


int main()
{
    output_argus(1, "test", 5.6f);
}

having the output
1test5.6

What if I would like using the fold expression appending an extra character '\n' to each element to get the following results?

1
test
5.6

Is that even possible? If yes, how?

like image 331
r0n9 Avatar asked Nov 08 '18 22:11

r0n9


1 Answers

What if I would like using the fold expression appending an extra character '\n' to each element to get the following results?

You can use the power of the comma operator

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

or, as suggested by Quentin (thanks) and as you asked, you can simply use \n instead of std::endl (to avoid multiple flushing of the stream)

 ((std::cout << args << '\n'), ...); 
like image 191
max66 Avatar answered Oct 04 '22 23:10

max66