1 /* Copyright (c) 2015-2019. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
12 #include <boost/variant.hpp>
15 #include <future> // std::future_error
17 #include <type_traits>
24 /** A value or an exception (or nothing)
26 * This is similar to `optional<expected<T>>`` but it with a Future/Promise
29 * Also the name is not so great.
36 return value_.which() > 0;
38 void set_exception(std::exception_ptr e)
40 value_ = std::move(e);
42 void set_value(T&& value)
44 value_ = std::move(value);
46 void set_value(T const& value)
51 /** Extract the value from the future
53 * After this, the value is invalid.
57 switch (value_.which()) {
59 T value = std::move(boost::get<T>(value_));
60 value_ = boost::blank();
64 std::exception_ptr exception = std::move(boost::get<std::exception_ptr>(value_));
65 value_ = boost::blank();
66 std::rethrow_exception(std::move(exception));
70 throw std::future_error(std::future_errc::no_state);
74 boost::variant<boost::blank, T, std::exception_ptr> value_;
78 class Result<void> : public Result<std::nullptr_t>
83 Result<std::nullptr_t>::set_value(nullptr);
87 Result<std::nullptr_t>::get();
92 class Result<T&> : public Result<std::reference_wrapper<T>>
95 void set_value(T& value)
97 Result<std::reference_wrapper<T>>::set_value(std::ref(value));
101 return Result<std::reference_wrapper<T>>::get();
105 /** Execute some code and set a promise or result accordingly
110 * promise.set_value(code());
113 * but it takes care of exceptions and works with `void`.
115 * We might need this when working with generic code because
116 * the trivial implementation does not work with `void` (before C++1z).
118 * @param code What we want to do
119 * @param promise Where to want to store the result
121 template <class R, class F> auto fulfill_promise(R& promise, F&& code) -> decltype(promise.set_value(code()))
124 promise.set_value(std::forward<F>(code)());
126 promise.set_exception(std::current_exception());
130 template <class R, class F> auto fulfill_promise(R& promise, F&& code) -> decltype(promise.set_value())
133 std::forward<F>(code)();
136 promise.set_exception(std::current_exception());
140 /** Set a promise/result from a future/result
144 * <pre>promise.set_value(future);</pre>
146 * but it takes care of exceptions and works with `void`.
148 * We might need this when working with generic code because
149 * the trivial implementation does not work with `void` (before C++1z).
151 * @param promise output (a valid future or a result)
152 * @param future input (a ready/waitable future or a valid result)
154 template <class P, class F> inline void set_promise(P& promise, F&& future)
156 fulfill_promise(promise, [&future] { return std::forward<F>(future).get(); });