C ++ 0x: the correct way to get lambda as a parameter by reference

What is the correct way to define a function that receives the parameter int->int lambda by reference?

 void f(std::function< int(int) >& lambda); 

or

 void f(auto& lambda); 

I am not sure that the last form is even legal syntax.

Are there other ways to determine the lambda parameter?

+62
c ++ lambda c ++ 11 function-prototypes function-parameter
Jun 23 2018-11-18T00:
source share
4 answers

You cannot have an auto parameter. You basically have two options:

Option # 1: use std::function , as you showed.

Option # 2: use the template parameter:

 template<typename F> void f(F &lambda) { /* ... */} 

Option # 2 may in some cases be more efficient, since it can avoid the potential heap allocation for the built-in object of the lambda function, but is possible only if f can be placed in the header as a template function. It can also increase compilation time and I-cache size, like any template. Note that it also may not have an effect, as if the lambda function object was small enough, it could be represented inline in the std::function object.

+67
Jun 23 '11 at 18:11
source share
β€” -

I would use template like:

 template<typename Functor> void f(Functor functor) { cout << functor(10) << endl; } int g(int x) { return x * x; } int main() { auto lambda = [] (int x) { cout << x * 50 << endl; return x * 100; }; f(lambda); //pass lambda f(g); //pass function } 

Output:

 500 1000 100 

Demo: http://www.ideone.com/EayVq

+29
Jun 23 '11 at 18:13
source share

I know that this question has already been answered, but when I was looking for the answer to this question, I was looking for something a little different from the answers here, and I think that this may have been what the OP hinted at, therefore here hope this helps someone else.

Say you have a function:

 void print(int n) { printf("%i ", n); } 

To pass the lambda to this function, you do the following:

 print([]{ return 3; }()); 

This will obviously lead to function 3. A more useful example specifically related to the OP question is a lambda, which takes an integer as a parameter and returns the int function to the final function:

 int x = 3; auto lambdaFunction = [](int input) { return (input + 1); }; print(lambdaFunction(x)); 

It is assumed that you do not follow the value or the link to the lambda, which you can do directly:

 // Pass by value print([=]{ return (x + 1); }()); // Pass by reference print([&]{ return (x + 1); }()); 
0
Jun 22 '17 at 3:57 on
source share

I know that it was 7 years old, but here, like no one else mentioned:

 void foo(void (*f)(int)){ std::cout<<"foo"<<std::endl; f(1); // calls lambda which takes an int and returns void } int main(){ foo([](int a){std::cout<<"lambda "<<a<<std::endl;}); } 

What are the findings:

 foo lambda 1 

No need for templates or std :: function

0
Apr 27 '19 at 23:32
source share



All Articles