1

Considering this piece of code

int main(int argc, char *argv[]) {
   string a = "hello world";
   void (*f) = []() {
      cout << a << endl;
   }
}

How can I define f such that the type of f is void (*f)(void)? Without using [&].

The motive is that I want to store in a struct this function f, but I don't want to give the struct a.

How do I proceed?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
truvaking
  • 347
  • 2
  • 10

1 Answers1

2

A lambda is only convertible to a function pointer if it does not capture anything (because captures amount to dynamic memory allocation, and would require destruction/deallocation later, which a function pointer type does not offer).

ClosureType::operator ret(*)(params)() :

This user-defined conversion function is only defined if the capture list of the lambda-expression is empty.

If you want to store a capturing lambda in a struct, you can store it as a std::function.

jtbandes
  • 115,675
  • 35
  • 233
  • 266