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?
You cannot have an
autoparameter. You basically have two options:Option #1: Use
std::functionas you have shown.Option #2: Use a template parameter:
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
fcan 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 thestd::functionobject.Don’t forget to use
std::forward<F&&>(lambda)when referring tolambda, as it is an r-value reference.