Considering C++11’s lambdas with the following code,
template <typename M>
void call(void (*f)(M), M m)
{
f(m);
}
int main()
{
call<int>([](int n) { }, 42); // OK
int r;
call<int>([&](int n) { r = n; }, 42); // KO
}
is there a signature difference between the lambdas that makes the second one incompatible with the argument of call?
I use g++ 4.6.1.
Side question: why can’t the parameter be inferred if I write call([](int n) { }, 42);?
Only a captureless lambda can be implicitly converted to function pointer.
A lambda that captures variables cannot be converted to a function pointer because it has state that needs to be maintained (the captured variables) and that state cannot be represented by a function pointer.
The type
Mcannot be inferred from the function arguments because a conversion is required to convert the lambda to a function pointer. That conversion inhibits template argument deduction. If you were to call the functioncallwith an actual function (e.g.,void f(int)), argument deduction would work just fine.