How does generic lambda work in C++14?

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, when auto appears at least once in the parameter list).

So your example:

auto glambda = [] (auto a) { return a; };

Will make glambda an instance of this type:

class /* unnamed */
{
public:
    template<typename T>
    T operator () (T a) const { return a; }
};

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:

The closure type for a non-generic lambda-expression has a public inline function call operator (13.5.4)
whose parameters and return type are described by the lambda-expression’s parameter-declaration-clause
and trailing-return-type respectively. For a generic lambda, the closure type has a public inline function call
operator member template (14.5.2) whose template-parameter-list consists of one invented type template-parameter
for each occurrence of auto in the lambda’s parameter-declaration-clause, in order of appearance
.
The invented type template-parameter is a parameter pack if the corresponding parameter-declaration declares
a function parameter pack (8.3.5). The return type and function parameters of the function call
operator template are derived from the lambda-expression’s trailing-return-type and parameter-declarationclause
by replacing each occurrence of auto in the decl-specifiers of the parameter-declaration-clause with
the name of the corresponding invented template-parameter.

Finally:

Is it similar to templates where for each different argument type compiler generates functions with the same body but changed types or is it more similar to Java’s generics?

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 🙂

Leave a Comment