mrs_lib
Various reusable classes, functions and utilities for use in MRS projects
Loading...
Searching...
No Matches
result_storage.hpp
1#ifndef MRS_LIB_CORO_INTERNAL_RESULT_STORAGE_HPP_
2#define MRS_LIB_CORO_INTERNAL_RESULT_STORAGE_HPP_
3
4
5#include <cstddef>
6#include <exception>
7#include <variant>
8
9
10namespace mrs_lib::coro::internal
11{
12
16 template <typename T>
18 {
19 private:
20 // Not enum class to allow usage in functions like std::get
21 enum State : size_t
22 {
23 empty = 0,
24 value = 1,
25 exception = 2,
26 };
27
28 public:
29 constexpr ResultStorage() noexcept : data_()
30 {
31 }
32
38 constexpr void set_value(T&& val) noexcept(std::is_nothrow_move_constructible_v<T>)
39 {
40 assert(data_.index() == State::empty);
41 data_.template emplace<State::value>(std::move(val));
42 }
43
49 void set_exception(std::exception_ptr eptr) noexcept
50 {
51 assert(data_.index() == State::empty || data_.valueless_by_exception());
52 data_.template emplace<State::exception>(std::move(eptr));
53 }
54
63 constexpr T get_value() &&
64 {
65 size_t state = data_.index();
66 if (state == State::exception)
67 {
68 std::rethrow_exception(std::get<State::exception>(data_));
69 }
70 assert(state == State::value);
71 return std::get<State::value>(std::move(data_));
72 }
73
74 private:
75 std::variant<std::monostate, T, std::exception_ptr> data_;
76 };
77
78} // namespace mrs_lib::coro::internal
79
80
81#endif // MRS_LIB_CORO_INTERNAL_RESULT_STORAGE_HPP_
A variant-like class for storing the result of non-void task.
Definition result_storage.hpp:18
constexpr T get_value() &&
Get previously stored result or exception.
Definition result_storage.hpp:63
constexpr void set_value(T &&val) noexcept(std::is_nothrow_move_constructible_v< T >)
Store result of task.
Definition result_storage.hpp:38
void set_exception(std::exception_ptr eptr) noexcept
Store exception into the result.
Definition result_storage.hpp:49