sandbox
Loading...
Searching...
No Matches
expected.hpp
1#ifndef LIBSBX_UTILITY_EXPECTED_HPP_
2#define LIBSBX_UTILITY_EXPECTED_HPP_
3
4#include <memory>
5#include <variant>
6#include <stdexcept>
7
8namespace sbx::utility {
9
10template<typename Type>
12
13public:
14
15 constexpr unexpected(const Type& value) noexcept
16 : _value{value} { }
17
18 constexpr ~unexpected() = default;
19
20 constexpr auto value() const noexcept -> const Type& {
21 return _value;
22 }
23
24private:
25
26 Type _value;
27
28}; // class unexpected
29
30struct bad_expected_access : public std::exception {
31
32 bad_expected_access() noexcept = default;
33
34 ~bad_expected_access() = default;
35
36 auto what() const noexcept -> const char* override {
37 return "bad expected access";
38 }
39
40}; // struct bad_expected_access
41
42template<typename Type, typename Error>
43class expected {
44
45public:
46
47 using value_type = Type;
48 using error_type = Error;
50
51 template<typename Other>
53
54 constexpr expected(const Type& value) noexcept
55 : _value{value} { }
56
57 constexpr expected(const unexpected_type& unexpected) noexcept
58 : _value{unexpected.value()} { }
59
60 constexpr auto has_value() const noexcept -> bool {
61 return std::holds_alternative<Type>(_value);
62 }
63
64 constexpr operator bool() const noexcept {
65 return has_value();
66 }
67
68 constexpr auto value() const -> const Type& {
69 if (!has_value()) {
70 throw bad_expected_access{};
71 }
72
73 return std::get<Type>(_value);
74 }
75
76 constexpr auto operator*() const -> const Type& {
77 return value();
78 }
79
80 constexpr auto operator->() const -> const Type* {
81 return &value();
82 }
83
84 constexpr auto error() const -> const Error& {
85 if (has_value()) {
86 throw bad_expected_access{};
87 }
88
89 return std::get<Error>(_value);
90 }
91
92private:
93
94 std::variant<Type, Error> _value;
95
96}; // class expected
97
98} // namespace sbx::utility
99
100#endif // LIBSBX_UTILITY_EXPECTED_HPP_
Definition: expected.hpp:43
Definition: expected.hpp:11
Definition: expected.hpp:30