Why do I have to surround parentheses in this fold expression?

1
2
3
4
5
6
template<typename... Args>
void printVariadic(Args... args) {
	(... , (std::cout << args << ' '));
}

printVariadic(1, 2, 3, 4);

This code can compile and print out 1 2 3 4. But if I remove the parentheses surrounding std::cout << args << ' ', there would be compile error:
1
2
3
4
5
6
template<typename... Args>
void printVariadic(Args... args) {
	(... , std::cout << args << ' ');
}

printVariadic(1, 2, 3, 4);

Comma operator has the lowest precedence, so I think even if I don't surround parentheses, there should be no problem after expansion. So, why do I have to surround std::cout << args << ' ' with parentheses in this fold expression? I'm using C++17.
Last edited on
Because the standard defines a unary left fold expression as:
( ... fold-operator cast-expression )

In your case the fold-operator is the comma operator. This is OK.

A cast-expression is one of the following:
unary-expression
( type-id ) cast-expression

The expression std::cout << args << ' ' is not a unary-expression and it doesn't start with a type within parentheses so it's not a cast-expression.

Unary-expressions are things like 123, var, foo(), arr[i]. Any expression that is surrounded by parentheses is also a unary-expression. That's why the parentheses are necessary in your code.
Topic archived. No new replies allowed.