I've encountered a situation that challenges my nascent understanding of C++ lambdas, and I've distilled it down to the following:
#include <iostream>
void test()
{
int (*func)();
func =
[]()->int {
std::cerr << "func()" << std::endl;
return 0;
};
int i = 0;
func =
[i]()->int {
std::cerr << "func(): i= " << i << std::endl;
return 0;
};
}
In the first case, I'm assigning a very simple lambda to a function pointer, and it seems to work as I would expect. What I'm trying to do in the second case is to provide the lambda with access to the value of i
. My understanding of [i]()->int {
code}
is that it defines a nameless function that takes no arguments, returns an int
and, through the magic of the C++11 unicorns, knows the current value of i
. I would expect that this lambda should be callable as int(*)()
.
test.cpp: In function ‘void test()’:
test.cpp:14:7: error: cannot convert ‘test()::__lambda1’ to ‘int (*)()’ in assignment
func =
^
It would seem that gcc 4.8.1 and 4.8.2 disagree with my assessment (4.4.1 refused to even discuss the matter).
This seems to suggest that the type of that second lambda is not assignment-compatible with the function pointer. I don't understand why that would be the case, given that that expression should be callable as "int(*)()
".
Where has my understanding (or the unicorns) failed me?