gpt4 book ai didi

c++ - boost 绑定(bind)到方法

转载 作者:行者123 更新时间:2023-11-28 06:13:44 24 4
gpt4 key购买 nike

我正在尝试使用 boost thread 对我的一个应用程序进行多线程处理。

我有问题的部分是 boost::bind

这是我正在尝试做的:

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

考虑:

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

CalculateRT 是一个方法:TransformType Class::CalculateRT(int i, int j) 如您所料,它返回 RT。

我想要的是能够绑定(bind)我的方法,获取它返回的内容 (RT),然后用类似的东西对其进行线程处理:

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

我很确定我将 RT 作为第二个参数来使用 bind 是错误的。

在浏览了其他一些 StackOverflow 问题之后,我尝试了这样的事情:

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

直到编译时,所有这些都不会在 VS2013 中显示错误,它会弹出:错误 C2825: 'F': must be a class or namespace when followed by '::' 错误。

感谢您的帮助!

最佳答案

您误解了 bind 的作用。它绑定(bind)参数。 IE。它可以通过绑定(bind)x=3Foo(x,y)变成Foo(3,y)。您不绑定(bind)返回值。

相反,您需要的是一个 lambda:[&RT, i](){RT = Class::CalculateRT(i, i - 1)

当然,如果CalculateRT 是一个非静态方法,那么您就需要一个来自某处的Class 对象。

使用:

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

当然,如果你想依赖RT的结果,你可以join()线程代替。但到那时,您真的需要一个线程和一个绑定(bind)函数吗?

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

关于c++ - boost 绑定(bind)到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com