As James said, only illiterate lambdas can be converted to function pointers. Lambdas that have state create object objects that implement operator()
, and member function pointers are incompatible with free function pointers.
When the compiler processes: [&](int n){ r = n; }
[&](int n){ r = n; }
it generates something like:
class __annonymous_lambda_type { int & r; public: __annonymous_lambda_type( int & r ) : r(r) {} void operator()( int n ) const { r = n; } } __lambda_instatiation;
The class must store the state of the lambda, in this case, a reference to an external object that will be changed when the lambda is executed. That void operator()(int)
cannot be bound to void (*)(int)
.
On the other hand, if a lambda has no status, it can be implemented as a free function, for example, in the case of []( int n ) { std::cout << "Hi" << n << std::endl ; }
[]( int n ) { std::cout << "Hi" << n << std::endl ; }
void __annonymous_lambda_function( int n ) { std::cout << "Hi " << n << std::endl; }
Since lambda does not need to save any state at all, and as such it can be stored as a simple function.
source share