条件 std::future 和 std::async

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 结果异步结果或 0 如果 ptrnullptr

上面的代码可以吗?我可以做类似的事情吗(将 'int' 分配给 'std::futture'?或者也许有更好的解决方案?

std::future have no conversion constructor 所以你的代码无效(如果你真的尝试编译代码你会注意到)。

你可以做的是使用默认构造的未来,然后在使用未来之前检查它是否 valid

您可以在不使用像这样的线程的情况下将值加载到未来:

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;

您也可以 return 为您的其他案例(使用不同的政策)std::future

std::future<int> f = pointer
    ? std::async(&Class::method, ptr)
    : std::async(std::launch::deferred, [](){ return 0;});