X-Git-Url: http://info.iut-bm.univ-fcomte.fr/pub/gitweb/simgrid.git/blobdiff_plain/74950d38bb412bfa1489d8ce0a8c5a194fe87a45..c04b15f5346d042218b4fb8357cace04585e067b:/include/xbt/future.hpp diff --git a/include/xbt/future.hpp b/include/xbt/future.hpp index 122d59093b..a374bec117 100644 --- a/include/xbt/future.hpp +++ b/include/xbt/future.hpp @@ -9,15 +9,21 @@ #include -#include #include +#include +#include +#include +#include namespace simgrid { namespace xbt { -/** A value or an exception +/** A value or an exception (or nothing) + * + * This is similar to `optional>`` but it with a Future/Promise + * like API. * - * The API is similar to the one of future and promise. + * Also the name is not so great. **/ template class Result { @@ -112,7 +118,7 @@ public: /** Extract the value from the future * - * After this the value is invalid. + * After this, the value is invalid. **/ T get() { @@ -144,7 +150,7 @@ private: }; template<> -class Result : public Result +class Result : public Result { public: void set_value() @@ -153,7 +159,7 @@ public: } void get() { - Result::get(); + Result::get(); } }; @@ -171,30 +177,40 @@ public: } }; -/** Fulfill a promise by executing a given code */ +/** Execute some code and set a promise or result accordingly + * + * Roughly this does: + * + *
+ *  promise.set_value(code());
+ *  
+ * + * but it takes care of exceptions and works with `void`. + * + * We might need this when working with generic code because + * the trivial implementation does not work with `void` (before C++1z). + * + * @param code What we want to do + * @param promise Where to want to store the result + */ template auto fulfillPromise(R& promise, F&& code) -> decltype(promise.set_value(code())) { try { - promise.set_value(code()); + promise.set_value(std::forward(code)()); } catch(...) { promise.set_exception(std::current_exception()); } } -/** Fulfill a promise by executing a given code - * - * This is a special version for `std::promise` because the default - * version does not compile in this case. - */ template auto fulfillPromise(P& promise, F&& code) -> decltype(promise.set_value()) { try { - (code)(); + std::forward(code)(); promise.set_value(); } catch(...) { @@ -202,6 +218,26 @@ auto fulfillPromise(P& promise, F&& code) } } +/** Set a promise/result from a future/result + * + * Roughly this does: + * + *
promise.set_value(future);
+ * + * but it takes care of exceptions and works with `void`. + * + * We might need this when working with generic code because + * the trivial implementation does not work with `void` (before C++1z). + * + * @param promise output (a valid future or a result) + * @param future input (a ready/waitable future or a valid result) + */ +template inline +void setPromise(P& promise, F&& future) +{ + fulfillPromise(promise, [&]{ return std::forward(future).get(); }); +} + } }