What is the right way to define a function that receives a int->int
lambda parameter by reference?
void f(std::function< int(int) >& lambda);
or
void f(auto& lambda);
I'm not sure the last form is even legal syntax.
Are there other ways to define a lambda parameter?
A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke ). If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.
Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };
Lambdas always capture objects, and they can do so by value or by reference.
You cannot have an auto
parameter. You basically have two options:
Option #1: Use std::function
as you have shown.
Option #2: Use a template parameter:
template<typename F> void f(F &lambda) { /* ... */}
Option #2 may, in some cases, be more efficient, as it can avoid a potential heap allocation for the embedded lambda function object, but is only possible if f
can be placed in a header as a template function. It may also increase compile times and I-cache footprint, as can any template. Note that it may have no effect as well, as if the lambda function object is small enough it may be represented inline in the std::function
object.
I would use template
as:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With