How does generic lambda work (auto
keyword as an argument type) in C++14 standard?
Is it based on C++ templates where for each different argument type compiler generates a new function with the same body but replaced types (compile-time polymorphism) or is it more similar to Java's generics (type erasure)?
Code example:
auto glambda = [](auto a) { return a; };
Best Answer
Generic lambdas were introduced in
C++14
.Simply, the closure type defined by the lambda expression will have a templated call operator rather than the regular, non-template call operator of
C++11
's lambdas (of course, whenauto
appears at least once in the parameter list).So your example:
Will make
glambda
an instance of this type:Paragraph 5.1.2/5 of the C++14 Standard Draft n3690 specifies how the call operator of the closure type of a given lambda expression is defined:
Finally:
As the above paragraph explains, generic lambdas are just syntactic sugar for unique, unnamed functors with a templated call operator. That should answer your question :)