Home >Backend Development >C++ >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 ! }
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!