[英]Conditional std::future and std::async
我需要做條件行為。
std::future<int> f = pointer ? std::async(&Class::method, ptr) : 0;
// ... Some code
x = f.get();
所以我想將ptr->method()
調用的x結果異步結果分配給x,如果ptr
是nullptr
,則分配為0。
上面的代碼可以嗎? 我可以這樣做嗎(將'int'分配給'std :: futture'?或者也許有更好的解決方案?
std::future
沒有轉換構造函數,因此您的代碼無效(如您實際上已嘗試編譯代碼那樣,您會注意到)。
您可以在不使用如下線程的情況下將值加載到將來:
std::future<int> f;
if ( pointer )
f = std::async(&Class::method, ptr);
else
{
std::promise<int> p;
p.set_value(0);
f = p.get_future();
}
// ... Some code
x = f.get();
但是,實現相同目標的一種更簡單的方法是:
std::future<int> f;
if ( pointer )
f = std::async(&Class::method, ptr);
// ... Some code
x = f.valid() ? f.get() : 0;
您還可以為其他情況返回std::future
(使用其他策略):
std::future<int> f = pointer
? std::async(&Class::method, ptr)
: std::async(std::launch::deferred, [](){ return 0;});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.