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