c++ - Create a "do-nothing" `std::function` with any signature? -


i create simple no-op std::function object arbitrary signature. end, i've created 2 functions:

template <typename result, typename... argsproto>   std::function<result(argsproto...)> getfuncnoop()   {     // "default-initialize-and-return" lambda     return [](argsproto...)->result { return {}; };   }  template <typename... argsproto>   std::function<void(argsproto...)> getfuncnoop()   {     // "do-nothing" lambda     return [](argsproto...)->void {};   } 

each of these works enough (obviously first version might create uninitialized data members in result object, in practice don't think of problem). second, void-returning version necessary because return {}; never returns void (this compile error), , can't written template-specialization of first because initial signature variadic.

so forced either pick between these 2 functions , implement one, or give them different names. really want initialize std::function objects in such way that, when called, nothing rather throwing exception. possible?

note the default constructor of std::function not want.

i don't having specify signature.

assuming have std::function implementation std::function<void()> can accept function pointer of type int(*)(), non-type erased noop object can cast std::function:

struct noop {   struct {     template<class t>     operator t(){ return {}; }     // optional reference support.  evil.     template<class t>     operator t&()const{ static t t{}; return t; }   };   template<class...args>   operator()(args&&...)const{return {};} }; 

if std::function not support conversion, add:

  template<class...args>   operator std::function<void(args...)>() {     return [](auto&&...){};   } 

which should handle case, assuming std::function sfinae friendly.

live example.

to use, use noop{}. if need function returning noop, inline noop getfuncnoop(){ return{}; }.

a side benefit if pass noop non-type erasing operation, don't pointless std::function overhead doing nothing.

the reference support evil because creates global object , propogates references on place. if 1 std::function<std::string&()> called, , resulting string modified, modified string used everywhere (and without synchronization between uses). plus allocating global resources without telling seems rude.

i'd =delete operator t& case instead, , generate compile-time error.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

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

How to use Authorization & Authentication in Asp.net, C#? -