[英]std::async on member function of member field
class Foo
{
private:
std::unique_ptr<Bar>& bar;
int retVal;
std::future<int> myFuture = std::async(std::launch::async, &Foo::bar->myMethod, this);
Foo(std::unique_ptr<Bar>& bar_) : bar(bar_) {}
}
I believe this sums up the topic, as this doesn't work. 我认为这可以概括主题,因为这不起作用。 How can I launch
myFuture
on Bar::myMethod
? 如何在
Bar::myMethod
上启动myFuture
?
You need to name Bar::myMethod
, and pass a (cv appropriate) Bar *
or Bar &
. 您需要命名
Bar::myMethod
,并传递(适当的cv) Bar *
或Bar &
。 That will look something like 看起来像
std::async(std::launch::async, &Bar::myMethod, bar.get());
Okay so, fixing some of the mess (ie adding everything that is missing) we can arrive at a simple solution using a lambda function: 好了,修复一些混乱(即添加所有丢失的东西),我们可以使用lambda函数获得一个简单的解决方案:
#include <future>
#include <iostream>
class Bar {
public:
int myMethod(void) {
std::cerr << "Hi!\n";
return 1;
}
};
class Foo {
private:
std::unique_ptr<Bar>& bar;
int retVal;
std::future<int> myFuture = std::async(std::launch::async, [this](void)->int{return bar->myMethod();});
public:
Foo(std::unique_ptr<Bar>& bar_) : bar(bar_) {}
};
int main(void) {
std::unique_ptr<Bar> bar = std::make_unique<Bar>();
Foo foo(bar);
return 0;
}
This might of course not be the only solution, nor the best in terms of performance. 当然,这可能不是唯一的解决方案,也不是最佳的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.