Pubby
Pubby

Reputation: 53037

What 'alternate grammar' does [[ appear in besides attributes?

I don't understand this:

(7.6.1) Two consecutive left square bracket tokens shall appear only when introducing an attribute-specifier. [Note: If two consecutive left square brackets appear where an attribute-specifier is not allowed, the program is ill formed even if the brackets match an alternative grammar production. —end note ] [Example: (slightly modified from source)

// ...
void f() {
int x = 42, y[5];
  // ...
  y[[] { return 2; }()] = 2; // error even though attributes are not allowed
                             // in this context.
}

What alternate grammar can [[ be used for? Would the example be valid if attributes didn't exist (and what does the example do)?

Upvotes: 6

Views: 395

Answers (1)

Xeo
Xeo

Reputation: 131789

The example creates a simple lambda, which is directly called and will just return 2. This will get the third element from the array and assign it to 2. Could be rewritten as follows:

int foo(){ return 2; }

int y[5];

y[foo()] = 2;

Or even

int y[5];

auto foo = []{ return 2; }; // create lambda

y[foo()] = 2; // call lambda

Now, if attributes didn't exist, the example would of course be well-formed, because the section you quoted wouldn't exist.

Upvotes: 2

Related Questions