设置临时值 std::future

Set value of temporary std::future

我有一个 return 是 std::pair<std::future<bool>,std::future_status> 的函数。在某些情况下,我希望 future.get() 始终 return true 并且我想知道是否有合法的方法来做到这一点。目前我正在做一些可怕的事情:

std::future<bool> tmp = std::async(std::launch::async,[]()->bool{return true;}); 
return std::make_pair(std::move(tmp), std::future_status::ready); 

有人知道将 tmp 的值设置为 true 的更好方法吗?

我不确定你想要达到什么效果,但是你可以使用一个std::promise直接设置一个std::future的值:

#include<future>

std::promise<bool> tmpPromise; //default construct promise

std::future<bool> tmp = tmpPromise.get_future(); //get future associated with promise

tmpPromise.set_value(true); //set future value

return std::make_pair(tmp, std::future_status::ready);