0

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.

John S
  • 3,035
  • 2
  • 18
  • 29
  • 2
    a lambda with a capture is fundamentally different from a free function, try `std::function` which works basically with any callable – 463035818_is_not_an_ai Dec 19 '18 at 17:10
  • if you are not allowed to change `HANDLER` you are out of luck – 463035818_is_not_an_ai Dec 19 '18 at 17:11
  • 1
    A capture-less lambda has no data it needs to store and so is safely convertible to a function pointer, but a lambda with a capture needs to store the captured data somewhere, and so can't be represented by just a function pointer. Use `std::function`. – alter_igel Dec 19 '18 at 17:11
  • HANDLER is from someone else's code, I can't change it. Should I be able to use `std::bind` here, or will I run into the same problem? – John S Dec 19 '18 at 17:48

0 Answers0