-
Notifications
You must be signed in to change notification settings - Fork 1
/
optional.h
84 lines (67 loc) · 1.78 KB
/
optional.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once
#include "cstdlib/cstddef.h"
#include "utility.h"
namespace firefly::std {
template <typename T>
class optional {
bool _ok;
T _val;
public:
constexpr optional(T&& val)
: _ok{ true }, _val{ val } {
}
constexpr optional(T const& val)
: _ok{ true }, _val{ val } {
}
constexpr optional()
: _ok{ false } {
}
constexpr optional(nullptr_t)
: _ok{ false } {
}
constexpr optional(const optional<T>& other)
: _ok{ other._ok }, _val{ other._val } {
}
constexpr optional(optional<T>&& other)
: _ok{ other._ok }, _val{ firefly::std::move(other._val) } {
}
template <typename U>
constexpr optional(const optional<U>& other)
: _ok{ other._ok }, _val{ other._val } {
}
template <typename U>
constexpr optional(optional<U>&& other)
: _ok{ other._ok }, _val{ firefly::std::move(other._val) } {
}
optional& operator=(optional const&) = default;
optional& operator=(optional&&) = default;
~optional() = default;
T* operator->() {
return &_val;
}
T& operator*() {
return _val;
}
operator bool() {
return _ok;
}
bool has_value() {
return _ok;
}
T& value() {
return _val;
}
T& value_or(T& val) {
if (has_value()) {
return _val;
}
return val;
}
T value_or(T val) {
if (has_value()) {
return _val;
}
return val;
}
};
} // namespace firefly::std