Home > Backend Development > C++ > Why Does `auto` Deduction of a C 11 Lambda Expression Differ from its Function Pointer Type?

Why Does `auto` Deduction of a C 11 Lambda Expression Differ from its Function Pointer Type?

Barbara Streisand
Release: 2024-12-24 17:57:19
Original
371 people have browsed it

Why Does `auto` Deduction of a C  11 Lambda Expression Differ from its Function Pointer Type?

Lambda Expression Type Deduction in C 11

In C 11, lambda expressions are versatile tools for creating anonymous functions. However, their underlying type deduction mechanism may not always be intuitive.

Consider the code snippet:

#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

The code assigns a lambda expression to both a function pointer and an auto variable. However, the assertion comparing their types fails. This raises a question: what is the true type of a lambda expression when deduced using auto?

Unlike what might be expected, lambda expressions do not inherently have a function pointer type. Instead, they translate to functor objects. Anything within the [] bracket becomes constructor arguments and functor members, while parameters within () become the functor's operator() parameters.

Lambda expressions that do not capture variables (empty [] brackets) can be converted to function pointers. However, the underlying type of the lambda itself remains a functor type, which is not necessarily the same as a function pointer.

Therefore, the assertion in the code snippet fails because the type of pFptr is a function pointer, while the type of pAuto is the functor type generated by the lambda expression.

The above is the detailed content of Why Does `auto` Deduction of a C 11 Lambda Expression Differ from its Function Pointer Type?. 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