Why is [] mutable {} not compiling?

This compiles:

[]{}; 

It's the same:

 []() mutable {}; 

But with this code, the compilers give me error messages:

 [] mutable {}; ^~~~~~~ error: lambda requires '()' before 'mutable' 

Is there any special reason?

+7
c ++ lambda c ++ 11 mutable
source share
2 answers

This is simply a consequence of how the grammar is written in the standard. I do not know whether this is supervision or not.

A lambda expression begins with a lambda introducer (parentheses), followed by an optional lambda declarator.

The lambda declaration contains an argument list, mutable attributes, an exception specifier, and a return type. All of this is optional, except for a list of arguments. Therefore, if a lambda declarator is present at all, there must be parentheses.

That's why you can not only have a mutable keyword.

+5
source share

In section 5.1.2 [expr.prim.lambda] in n4296 (this is the final C ++ 14 project), that is exactly how it comes out of the grammar. mutable is only allowed in a lambda declarator that includes brackets. The whole lambda declarator is optional (so you can omit the brackets).

+1
source share

All Articles