I'm getting a compiler error when trying to define a lambda capturing this
in the constructor of an object. It looks like this:
typedef int (*HANDLER)(char*, int);
struct Foo {
bool member;
Foo() {
HANDLER h1 = [](char* one, int two)->int {
return 0; // fine
};
HANDLER h2 = [](char* one, int two)->int {
member = false; // error: 'this' was not captured - understood
return 0;
};
HANDLER h3 = [this](char* one, int two)->int {
member = false; // ok now but other error as below
return 0;
};
}
};
h1
is trivial and compiles fine. h2
doesn't compile, because the member variable member
is not captured. This also makes sense. But when I add this
to the capture to get access to member
, I get an error message that I'm struggling to parse:
mcve.cpp: In constructor ‘Foo::Foo()’:
mcve.cpp:16:11: error: cannot convert ‘Foo::Foo()::<lambda(char*, int)>’ to ‘HANDLER {aka int (*)(char*, int)}’ in initialization
};
^
This is using gcc 4.9.1 with -std=c++14, though I get the same error with clang-1000.11.45.5 on a Mac. Note that the HANDLER
function pointer typedef is something I'm working with from an external library.