Understanding Generic Lambdas in C 14 Variant of Auto Keyword
In C 14, generic lambdas, a type of lambda expression with auto keyword as an argument type, provide enhanced flexibility. Contrary to C 11 lambdas with a non-template call operator, generic lambdas have a templated call operator within the closure type they define.
For example, the following code demonstrates a generic lambda:
auto glambda = [](auto a) { return a; };
In this case, the closure type of glambda will be defined as:
class /* unnamed */ { public: template<typename T> T operator () (T a) const { return a; } };
This means that glambda is an instance of a unique, unnamed functor with a templated call operator. Each occurrence of auto in the lambda's parameter declaration corresponds to an invented type template parameter, allowing the call operator to handle arguments of different types.
The C 14 standard (n3690) specifies that the call operator of the closure type for a generic lambda has a template-parameter-list with one invented type template-parameter for each auto in the lambda's parameter-declaration-clause. The return type and function parameters are derived from the lambda's trailing-return-type and parameter-declaration-clause with auto replaced by the name of the corresponding invented template-parameter.
In summary, generic lambdas in C 14 represent unique, unnamed functors with templated call operators. This differs from C template-based polymorphism, where the compiler generates new functions with replaced types for each argument type. It is more closely aligned with Java's generics, which involve type erasure during compilation.
The above is the detailed content of How Do C 14 Generic Lambdas Achieve Type Flexibility Using the `auto` Keyword?. For more information, please follow other related articles on the PHP Chinese website!