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>
16 #include <type_traits>
23 /** A value or an exception (or nothing)
25 * This is similar to `optional<expected<T>>`` but it with a Future/Promise
28 * Also the name is not so great.
35 return value_.which() > 0;
37 void set_exception(std::exception_ptr e)
39 value_ = std::move(e);
41 void set_value(T&& value)
43 value_ = std::move(value);
45 void set_value(T const& value)
50 /** Extract the value from the future
52 * After this, the value is invalid.
56 switch (value_.which()) {
58 T value = std::move(boost::get<T>(value_));
59 value_ = boost::blank();
63 std::exception_ptr exception = std::move(boost::get<std::exception_ptr>(value_));
64 value_ = boost::blank();
65 std::rethrow_exception(std::move(exception));
69 throw std::logic_error("Invalid result");
73 boost::variant<boost::blank, T, std::exception_ptr> value_;
77 class Result<void> : public Result<std::nullptr_t>
82 Result<std::nullptr_t>::set_value(nullptr);
86 Result<std::nullptr_t>::get();
91 class Result<T&> : public Result<std::reference_wrapper<T>>
94 void set_value(T& value)
96 Result<std::reference_wrapper<T>>::set_value(std::ref(value));
100 return Result<std::reference_wrapper<T>>::get();
104 /** Execute some code and set a promise or result accordingly
109 * promise.set_value(code());
112 * but it takes care of exceptions and works with `void`.
114 * We might need this when working with generic code because
115 * the trivial implementation does not work with `void` (before C++1z).
117 * @param code What we want to do
118 * @param promise Where to want to store the result
120 template <class R, class F> auto fulfill_promise(R& promise, F&& code) -> decltype(promise.set_value(code()))
123 promise.set_value(std::forward<F>(code)());
125 promise.set_exception(std::current_exception());
129 template <class P, class F> auto fulfill_promise(P& promise, F&& code) -> decltype(promise.set_value())
132 std::forward<F>(code)();
135 promise.set_exception(std::current_exception());
139 /** Set a promise/result from a future/result
143 * <pre>promise.set_value(future);</pre>
145 * but it takes care of exceptions and works with `void`.
147 * We might need this when working with generic code because
148 * the trivial implementation does not work with `void` (before C++1z).
150 * @param promise output (a valid future or a result)
151 * @param future input (a ready/waitable future or a valid result)
153 template <class P, class F> inline void set_promise(P& promise, F&& future)
155 fulfill_promise(promise, [&future] { return std::forward<F>(future).get(); });