Is []<typename>(){} a valid lambda definition?

In N4140 5.1.2 [expr.prim.lambda], a Lambda expression is defined as

lambda-introducer lambda-declaratoropt compound-statement

where a "lambda-introducer" is the [], enclosing an optional "lambda-capture" and "lambda-declaratoropt" is the stuff starting with "( parameter-declaration-clause )".

[]<typename>(){}

does not meet that requirement because there is something between the lambda introducer and the lambda declarator, so it is not a valid lambda expression.

Thus, your example code is not valid C++ and should be rejected by the compiler.


As this is also tagged gcc, I clicked through the list of GNU C++ extensions. I did not find any extension that would make the syntax in question legal in GNU C++.

However, according to Section 4 of this proposal (P0428R0), which proposes to add templated lambdas to C++, gcc got an experimental implementation of the aforementioned paper in 2009. This probably explains why gcc doesn't complain here.


It seems to be a GCC extension (templated lambdas).

#include <iostream>

int main() {
    auto l = []<typename T>(T const& x){ std::cout << __PRETTY_FUNCTION__ << " " << x << std::endl;};
    l(42);
    l("Hello world");
}

results in

main()::<lambda(const T&)> [with T = int] 42
main()::<lambda(const T&)> [with T = char [12]] Hello world