9

Is the following generic (polymorphic) lambda legal C++14?

auto f = [](auto x[3]) {
    x[0];
    x[1];
    // etc.
};

GCC and Clang 4 accept the code, but Visual Studio 2017 does not. Is it legal?

error C3318: 'auto [3]': an array cannot have an element type that contains 'auto'
cpplearner
  • 13,776
  • 2
  • 47
  • 72
Petter
  • 37,121
  • 7
  • 47
  • 62

1 Answers1

11

It is illegal.

[dcl.array]/1, emphasis mine:

In a declaration T D where D has the form

D1 [ constant-expressionopt ] attribute-specifier-seqopt

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type; if the type of the identifier of D contains the auto type-specifier, the program is ill-formed.

Community
  • 1
  • 1
cpplearner
  • 13,776
  • 2
  • 47
  • 72
  • Yeah, expect that for function definitions, this is not an array declaration, is it? – StoryTeller - Unslander Monica Aug 27 '17 at 09:09
  • 1
    @StoryTeller It is an array declaration, even though it will be transformed into pointer type later. – cpplearner Aug 27 '17 at 09:14
  • You know, you have a point. If you try to specify an array with a negative size for the function parameter, GCC and Clang complain. So this seems like a non-standard extension for the case of `auto` alone. – StoryTeller - Unslander Monica Aug 27 '17 at 09:18
  • 4
    This depends on whether you do this check directly on the generic lambda's *parameter-declaration-clause*, or instead only check it after it is transformed with invented template parameters. I also have a suspicion that this is intended to be allowed. +1 though. – T.C. Aug 27 '17 at 09:22
  • @T.C. - Intended or not, it'd be nice if Clang and GCC were consistent. They reject an invalid declaration based on a negative size specifier, but accept another ostensibly invalid declaration. – StoryTeller - Unslander Monica Aug 27 '17 at 09:38