I am using a std::future<T>
to store the result of an optionally asynchronous operation. Depending on arguments to a function the operation is either asynchronous or synchronous. In the synchronous case I have a value that I want to store in a future
. How do I best do this?
Examples given in https://en.cppreference.com/w/cpp/thread/future is:
future
from apackaged_task
future
from anasync()
future
from apromise
But there isn't a make_future
, nor does the future
constructor allow creating a fulfilled future
from a value. So I created a helper function for doing just that, by going through a promise
like this:
template <typename T>
std::future<T> make_future(T&& t)
{
std::promise<T> p;
p.set_value(std::forward<T>(t));
return p.get_future();
}
Is this a valid way to create a std::future<T>
from a T
?
Is there a better way to create a std::future<T>
from a T
?
Aucun commentaire:
Enregistrer un commentaire