我需要做有条件的行为。
std::future<int> f = pointer ? std::async(&Class::method, ptr) : 0;
// ... Some code
x = f.get();
所以我想将 ptr->method()
调用的异步结果分配给 x result 或如果 ptr
是 nullptr
则为 0 .
上面的代码可以吗?我可以做类似的事情吗(将“int”分配给“std::futture”?或者也许有更好的解决方案?
最佳答案
std::future
没有转换 constructor所以你的代码无效(如果你真的尝试编译代码,你会注意到)。
你可以做的是使用默认构建的 future ,然后检查它是否是 valid在你使用 future 之前。
关于c++ - 条件 std::future 和 std::async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36833124/