I have a one-dimensional function minimizer. Right now I'm passing it function pointers. However many functions have multiple parameters, some of which are held fixed. I have implemented this using functors like so
template <class T>
minimize(T &f) {
}
Functor f(param1, param2);
minimize<Functor>(f);
However the functor definition has lots of crud. Boost::bind looks cleaner. So that I could do:
minimize(boost:bind(f,_1,param1,param2))
However I'm not clear what my minimize
declaration should like like using boost::bind
. What type of object is boost::bind
? Is there an easy pattern for this that avoids the boilerplate of functors but allows multiple parameter binding?
Change the parameter to a value parameter. Function objects are intentionally light weight, and
boost::bind
certainly is, specially crafted to fit in within space of a few bytes usingboost::compressed_pair
and what not.Then you can pass it the result of
boost::bind
. Remember thatboost::bind
is actually a function template that returns some object of some type. So havingminimize
have a non-const reference parameter couldn't work.You can just use
boost::function
. I thinkboost::bind
does have its own return type, but that is compatible withboost::function
. Typical use is to make a typedef for the function:and then you can pass any compatible function with
boost::bind
:I hope that is what you want.
It also works with methods by passing the
this
pointer for the call as second parameter toboost::bind
.I would define minimize() this way:
Then you could call minimize() like this:
First, you are taking your template argument as a ref-to-non-const, so the temporary returend by boost::bind won't bind to it. So you can use it like:
But if you wanted to use this with your Functors as well, they would have to have a const operator(). So perhaps by value is better:
I believe having the return be T::result_type will force a T to be a boost::function (rather than the complicated type bind returns), but I'm not 100%