Home > Backend Development > C++ > What is the True Type of a C 11 Lambda Expression?

What is the True Type of a C 11 Lambda Expression?

Susan Sarandon
Release: 2024-12-10 10:06:12
Original
292 people have browsed it

What is the True Type of a C  11 Lambda Expression?

Lambda Type Inference with "auto" in C 11

The type of a lambda expression in C 11 is subject to debate, with some believing it to be a function pointer. However, consider the following demonstration:

#define LAMBDA [] (int i) -> long { return 0; }
int main()
{
    long (*pFptr)(int) = LAMBDA;  // ok
    auto pAuto = LAMBDA;  // ok
    assert(typeid(pFptr) == typeid(pAuto));  // assertion fails !
}
Copy after login

This code contradicts the assumption that lambdas have a function pointer type. So, what is the true nature of their type?

Unveiling the Lambda's True Identity

Contrary to popular belief, lambda expressions have an unspecified type. They are simply syntactic conveniences for functors. During compilation, a lambda transforms into a functor:

  • Elements within the [] brackets become constructor parameters and functor object members.
  • Parameters enclosed in () are converted into parameters for the functor's operator().

Lambdas with no variable captures (empty [] brackets) can technically be converted into function pointers. However, this conversion is not supported by all compilers (e.g., MSVC2010).

Important Distinction

While a lambda that captures no variables can act as a function pointer, its underlying type remains unspecified. It is not a function pointer but rather an unspecified functor type.

The above is the detailed content of What is the True Type of a C 11 Lambda Expression?. 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