Template argument for function type in C++ -


here, wrapper::set should able take function or function object matches int(int) signature, , store std::function. should work function pointers, lambdas, objects operator(), std::bind expressions, etc.

#include <functional>  struct wrapper {     using function_type = int(int);      std::function<function_type> func_;      template<typename func> void set(func func) { func_ = func; } }; 

what best form of set works in cases? i.e. 1 of

  • set(func func) { func_ = func; }
  • set(func&& func) { func_ = std::forward<func>(func); }
  • set(func& func) { func_ = func; }
  • set(const func& func) { func_ = func; }

the simplest version:

void set(std::function<function_type> f) {     func_ = std::move(f); } 

the complex version:

template <class f,     class = std::enable_if_t<std::is_assignable<std::function<function_type>&, f&&>::value>     > void set(f&& f) {     func_ = std::forward<f>(f); } 

there's no reason else. both of these handle every case gracefully , correctly, simple case has move, std::function isn't expensive operation, prefer simple version unless have compelling, proven performance requirement need complex one.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -