Home > Backend Development > C++ > How Do Generic Lambdas in C 14 Work?

How Do Generic Lambdas in C 14 Work?

Susan Sarandon
Release: 2024-12-06 00:53:11
Original
143 people have browsed it

How Do Generic Lambdas in C  14 Work?

Understanding Generic Lambdas in C 14

Introduced in C 14, generic lambdas provide a means to write lambda expressions that operate on values of any type. However, the question arises: how does this mechanism function?

Implementation of Generic Lambdas

Unlike regular lambdas in C 11, generic lambdas employ a templated call operator in their closure type. When the [auto](https://en.cppreference.com/w/cpp/keyword/auto) keyword appears in the parameter list, the compiler generates a templated call operator rather than a standard one.

Example:

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

This code generates a closure type with the following call operator:

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

Standard Definition

According to paragraph 5.1.2/5 of the C 14 Standard Draft n3690, the call operator of a generic lambda's closure type has the following properties:

  • Each occurrence of [auto](https://en.cppreference.com/w/cpp/keyword/auto) in the parameter list corresponds to an invented type template parameter.
  • The call operator's return type and function parameters are derived from the lambda's trailing return type and parameter declaration clause by replacing each [auto](https://en.cppreference.com/w/cpp/keyword/auto) with the invented template parameter's name.

Similarity to C Templates vs. Java Generics

Generic lambdas are similar to C templates in that the compiler generates unique functions with different argument types based on the template parameter. However, they differ from Java generics, which utilize type erasure at runtime to maintain type information at compile time. Generic lambdas, on the other hand, create statically specialized closures with explicit types.

The above is the detailed content of How Do Generic Lambdas in C 14 Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template