tags:

views:

1017

answers:

4

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?

+3  A: 

You can just use boost::function. I think boost::bind does have it's own return type, but that is compatible with boost::function. Typical use is to make a typedef for the function:

typedef boost::function<bool(std::string)> MyTestFunction;

and then you can pass any compatible function with boost::bind:

bool SomeFunction(int i, std::string s) { return true; }
MyTestFunction f = boost::bind(SomeFunction, 42, _1);
f("and then call it.");

I hope that is what you want.

It also works with methods by passing the this pointer for the call as second parameter to boost::bind.

OregonGhost
Beat me to it...
sheepsimulator
... though only by a few seconds ;)
OregonGhost
+1  A: 

I would define minimize() this way:

minimize(boost::function< return_type(param_type1,param_type2,param_type3,...)> f)
{
    ...
}

Then you could call minimize() like this:

minimize(boost::bind(&class::function,actual_object,_1,_2,_3,...));
sheepsimulator
+2  A: 

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 using boost::compressed_pair and what not.

template <class T>
void minimize(T f) {
}

Then you can pass it the result of boost::bind. Remember that boost::bind is actually a function template that returns some object of some type. So having minimize have a non-const reference parameter couldn't work.

Johannes Schaub - litb
+1  A: 

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:

template <class T>
T::result_type minimize(const T &f) {
}

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:

 template <class T>
 T::result_type minimize(T f) {
 }

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%

Todd Gardner