Generic Lambdas in C 14
In C 14, generic lambdas allow defining lambdas with auto as an argument type, enabling type-generic behavior. Understanding how they work sheds light on their underlying mechanisms.
Templated Call Operator
Generic lambdas define a closure type with a templated call operator rather than a non-template one like C 11 lambdas. This means that when auto appears in the parameter list, the compiler creates a function template for the call operator.
Example:
auto glambda = [](auto a) { return a; };
The above lambda creates an instance of the following type:
class /* unnamed */ { public: template<typename T> T operator () (T a) const { return a; } };
Type Erasure vs. Template Polymorphism
Generic lambdas are closer to Java's generics, which employ type erasure. Unlike C templates, which generate multiple functions with different types, generic lambdas create a single function with a type-erasing call operator.
Type Parameter List
The generic lambda's call operator template includes a template parameter list for each occurrence of auto in the parameter declaration. The type of each template parameter corresponds to the type of the corresponding variable.
Conclusion:
Generic lambdas in C 14 enable type-generic programming by defining lambda expressions with a templated call operator. This provides a concise way to create type-erasing functions similar to Java's generics.
The above is the detailed content of How Do C 14 Generic Lambdas Achieve Type-Generic Behavior?. For more information, please follow other related articles on the PHP Chinese website!