c++ - Setter of a lambda function? -


consider following dumb example :

class myclass {     public:         template <class function>          inline double f(double x, function&& function)         {             return function(x);         } }; 

with class, can call myclass::f(x, function), lambda function execute on x, (i hope) no overhead. question : equivalent function settable member of myclass ?

class myclass {     public:         inline double f(double x)         {             return _function(x);         }     // setter , type of protected member _function ? }; 

lambda functions (as other types of "callable" functions) can wrapped , stored using std::function template class, found in <functional> header. template parameter function signature syntax

returntype(argumenttype1, argumenttype2, ...) 

so in case whole function wrapper type becomes

std::function<double(double)> 

and thus, code becomes

class myclass {     public:         inline double f(double x)         {             return _function(x);         }         void setfunction(std::function<double(double)> && f)         {             _function = f;         }     private:         std::function<double(double)> _function; }; 

std::function "more" wrapper function pointers. might know, lambda functions can capture part of variable context, needs stored somewhere. std::function transparently.

note std::function not support overloaded signatures / templated call operators functors. when assigning functor call-operator signature t operator()(t value) std::function<double(double)>, can called signature. there no std::function<t(t)> (unless t known, such template parameter of class).


an alternative might more efficient in cases (you need benchmark / profile it), make whole class template class function type parameter being template parameter. can store function member:

template<typename function> class myclass {     public:         myclass(function && f) :             _function(f)         {}         inline double f(double x)         {             return _function(x);         }     private:         function _function; }; 

in order create such object, need specify template parameter, this:

auto mylambda = [](double x){ return x * 0.25; }; myclass<decltype(mylambda)> myobject { mylambda }; 

to avoid ugly syntactic overhead, add "maker" function takes advantage of template type deduction:

template<typename function> auto makemyclass(function && f) -> myclass<function> {     return myclass<function>(f); } 

then, code becomes more readable, use of auto again:

auto mylambda = [](double x){ return x * 0.25; }; auto myobject = makemyclass(mylambda); 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -