How to pass C ++ functor rvalue link to lambda capture?

I have the following function

template<class Function> void f(Function&& g) { h(..., [&g](){g();}); } 

This is a f function that takes a function, lambda, or functor as an argument. Inside, it calls the function h , to which I pass lambda as an argument that calls g , and gets g by capturing.

  • Should I pass g or &g to the lambda capture field?
  • Will the functor with the above code be copied?
+5
source share
3 answers

If you commit g by reference, that is, with the &g syntax specified in your snippet, the copy will fail. This is the preferred method. You should only copy if lambda can be called after completion of f , which potentially implies the destruction of g . In this case, shipping may be cheaper:

 template<class Function> void f(Function&& g) { h(…, [g=std::forward<Function>(g)] {g();}); } 
+2
source

You create a lambda that takes no arguments and returns nothing. But you already have such a functor: g !. You should just forward it:

 template<class Function> void f(Function&& g) { h(..., std::forward<Function>(g)); } 
+1
source

You can do it:

 template<class Function> void f(Function&& g) { Function f(std::move(g)); int additional = 0; h(..., [&f, additional](){f(additional);}); } 
+1
source

All Articles