c++ - Should I pass a lambda by const reference. -


typically use following pattern when accepting lambda argument function (a template class passed-by-value):

template <class function> void higherorderfunction(function f) {      f(); } 

does copy (the closure of) argument? if so, there wrong accepting lambda const reference instead?

template <class function> void higherorderfunction(const function& f) {   f(); } 

a simple test seems indicate works fine, want know if there special considerations should aware of.

if pass value copy closure object (assuming don't define lambda inline, in case moved). might undesirable if state expensive copy, , fail compile if state not copyable.

template <class function> void higherorderfunction(function f);  std::unique_ptr<int> p; auto l = [p = std::move(p)] {}; // c++14 lambda init capture higherorderfunction(l);         // doesn't compile because l non-copyable                                  // due unique_ptr member higherorderfunction([p = std::move(p)] {}); // still works, closure object moved 

if pass const reference, cannot pass mutable lambda modifies data members argument higherorderfunction() because mutable lambda has non-const operator(), , cannot invoke on const object.

template <class function> void higherorderfunction(function const& f);  int = 0; higherorderfunction([=]() mutable { = 0; }); // not compile 

the best option use forwarding reference. higherorderfunction can accept either lvalues or rvalues caller passes.

template <class function> void higherorderfunction(function&& f) {      std::forward<function>(f)(); } 

this allows simple cases ones mentioned above compile. discussion of why std::forward should used, see this answer.

live demo


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -