3
void f(int a, void(*b)(int))
{
   b(a);
}

int main()
{
  int a = 5;
  int b = 6;

  f(10, [a, b](int x) { cout << a+b+x; });

  return 0;
}

If I won't use 'a' and 'b' variables, everything works good, otherwise, C++ returns:

error: cannot convert 'main()::<lambda(int)>' to 'void (*)(int)''

note: initializing argument 2 of 'void f(int, void (*)(int))'

1 Answers1

3

Lambdas with captures can't convert to function pointer.

You can use std::function as parameter type instead. e.g.

void f(int a, std::function<void(int)> b)
{
   b(a);
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405