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 ! }
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:
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!