I had a perception that, type of a lambda is a function pointer. When I performed following test, I found it to be wrong (demo).
#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 !
}
Is above code missing any point? If not then, what is the typeof
a lambda expression when deduced with auto
keyword ?
Best Answer
The type of a lambda expression is unspecified.
But they are generally mere syntactic sugar for functors. A lambda is translated directly into a functor. Anything inside the
[]
are turned into constructor parameters and members of the functor object, and the parameters inside()
are turned into parameters for the functor'soperator()
.A lambda which captures no variables (nothing inside the
[]
's) can be converted into a function pointer (MSVC2010 doesn't support this, if that's your compiler, but this conversion is part of the standard).But the actual type of the lambda isn't a function pointer. It's some unspecified functor type.