How do I use boost.lambda with boost.thread to get

2019-07-20 21:26发布

I'm trying to do something like this:

using namespace boost::lambda;
using boost::thread;

int add(int a, int b) {return a+b;}

int sum, x=2, y=6;
thread adder(var(sum) = add(_1, _2), x, y);
adder.join();
cout << sum;

I get a compile error:

cannot convert parameter 1 from 'boost::arg' to 'int'

1条回答
放我归山
2楼-- · 2019-07-20 22:05

You’re really close actually! The problem is that you’re directly calling add() with Lambda’s placeholders—it’s not being evaluated lazily inside the lambda, but right away.

Here’s a fixed version:

using namespace boost::lambda;
using boost::thread;

int sum, x=2, y=6;
thread adder(var(sum) = _1 + _2, x, y);
adder.join();
cout << sum;

And if you really want to use the add function, you'd use bind:

using namespace boost::lambda;
using boost::thread;

int add(int a, int b) {return a+b;}

int sum, x=2, y=6;
thread adder(var(sum) = bind(add, _1, _2), x, y);
adder.join();
cout << sum;
查看更多
登录 后发表回答