lundi 13 janvier 2020

Best way to create a std::future

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:

  1. future from a packaged_task
  2. future from an async()
  3. future from a promise

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