Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Lambda As Argument In Function [duplicate]

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))'

like image 583
Abdul Axundzade Avatar asked Feb 18 '26 02:02

Abdul Axundzade


1 Answers

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);
}
like image 173
songyuanyao Avatar answered Feb 19 '26 14:02

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!