Boost Bind to Method

185 views Asked by At

I'm trying to use boost thread to multi-thread one of my applications.

The part I have an issue with is the boost::bind.

Here is what I am trying to do :

boost::bind(&Class::CalculateRT(i, i - 1), RT));

Considering :

RT is a TransformType 
typedef std::pair<Eigen::Matrix3d, Eigen::Vector3d> TransformType;

And CalculateRT is a method : TransformType Class::CalculateRT(int i, int j) which returns, as you can guess, RT .

What I want is to be able to bind my method, get what it returns (RT) and then thread it with something like :

boost::thread MultiThreadingRTCalculation(boost::bind(&Class::CalculateRT(i, i - 1), RT));

I'm pretty sure I'm using bind wrong by putting RT as second argument.

After looking through some other StackOverflow questions, I tried something like this :

boost::function<TransformType()> BoostFunction(boost::bind(&Class::CalculateRT(i, i - 1), RT));

All of these do not show an error in VS2013 until compile time, which pops a : error C2825: 'F': must be a class or namespace when followed by '::' error.

Thanks for the help !

2

There are 2 answers

14
Hcorg On BEST ANSWER

Class::CalculateRT(i, i - 1) is a function call, and you try to take address of call itself...

try something like: boost::bind(&Class::CalculateRT, i, i - 1) (address to bind to, arguments follow).

boost::ref(i) might be needed if you want it to return different values for different i.

Is this static method? Then it needs value for this in bind.

RT will be result of binding call:

boost::function<TransformType()> boundFunction = bind(........);
TransformType RT = boundFunction();
2
MSalters On

You're misunderstanding what bind does. It binds arguments. I.e. It can turn Foo(x,y) into Foo(3,y) by binding x=3. You don't bind return values.

Instead, what you need is a lambda: [&RT, i](){RT = Class::CalculateRT(i, i - 1)

Of course, if CalculateRT is a non-static method, then you need a Class object from somewhere.

To use:

TransformType RT;
auto boundFunction = [&RT, i](){RT = Class::CalculateRT(i, i - 1);
std::thread(boundFunction).detach(); // Doesn't wait for the assignment!

Of course, if you want to rely on the result of RT, you can join() the thread instead. But at that point, do you really need a thread and a bound function?

 auto background = std::sync(std::launch::async, &Class::CalculateRT, i,i-1);
 // Do stuff in the foreground.
  RT = background.get();