Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass lambda to a lambda?

Tags:

c++

c++11

lambda

I have not managed to find why this code does not work:

#include <iostream>
#include <functional>

using namespace std;

int main()
{
  auto xClosure = [](const function<void(int&)>& myFunction) {
    myFunction(10);};

  xClosure([]
       (int& number) -> void
       {cout<<number<<endl;
       });
  return 0;
}

It returns:

g++ test.cc -o test -std=c++14
 test.cc:9:5: error: no matching function for call to object of type 'const function<void
  (int &)>'
like image 450
Draif Kroneg Avatar asked Aug 19 '26 05:08

Draif Kroneg


1 Answers

This has nothing to do with lambdas:

void test(const function<void(int&)>& myFunction) {
  myFunction(10);
}

this fails to compile for the same reason; you cannot bind the literal 10 to an int&.

Maybe you meant

const function<void(int)>& myFunction

doing so and also modifying the signature of your lambda should make your code compile.

like image 191
Yakk - Adam Nevraumont Avatar answered Aug 21 '26 00:08

Yakk - Adam Nevraumont



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!