libfilezilla
Loading...
Searching...
No Matches
optional.hpp
Go to the documentation of this file.
1#ifndef LIBFILEZILLA_OPTIONAL_HEADER
2#define LIBFILEZILLA_OPTIONAL_HEADER
3
4
9namespace fz {
10
18template<typename T>
20{
21public:
22 sparse_optional() noexcept = default;
23 explicit sparse_optional(T const& v);
24
26 explicit sparse_optional(T * v) noexcept;
27
31
32 void clear();
33
34 explicit operator bool() const { return v_ != nullptr; };
35
36 T& operator*() { return *v_; }
37 T const& operator*() const { return *v_; }
38
39 T* operator->() { return v_; }
40 T const* operator->() const { return v_; }
41
42 bool operator==(sparse_optional<T> const& cmp) const;
43 inline bool operator!=(sparse_optional<T> const& cmp) const { return !(*this == cmp); }
44 bool operator<(sparse_optional<T> const& cmp) const;
45
46 sparse_optional<T>& operator=(sparse_optional<T> const& v);
47 sparse_optional<T>& operator=(sparse_optional<T> && v) noexcept;
48private:
49 T* v_{};
50};
51
52template<typename T>
54 : v_(new T(v))
55{
56}
57
58template<typename T>
63
64template<typename T>
66{
67 if (v) {
68 v_ = new T(*v);
69 }
70 else {
71 v_ = nullptr;
72 }
73}
74
75template<typename T>
76sparse_optional<T>::sparse_optional(sparse_optional<T> && v) noexcept
77{
78 v_ = v.v_;
79 v.v_ = nullptr;
80}
81
82template<typename T>
83sparse_optional<T>::~sparse_optional()
84{
85 delete v_;
86}
87
88template<typename T>
89void sparse_optional<T>::clear()
90{
91 delete v_;
92 v_ = nullptr;
93}
94
95template<typename T>
96sparse_optional<T>& sparse_optional<T>::operator=(sparse_optional<T> const& v)
97{
98 if (this != &v) {
99 T* value{};
100 if (v.v_) {
101 value = new T(*v.v_);
102 }
103 delete v_;
104 v_ = value;
105 }
106
107 return *this;
108}
109
110template<typename T>
111sparse_optional<T>& sparse_optional<T>::operator=(sparse_optional<T> && v) noexcept
112{
113 if (this != &v) {
114 delete v_;
115 v_ = v.v_;
116 v.v_ = nullptr;
117 }
118
119 return *this;
120}
121
122template<typename T>
123bool sparse_optional<T>::operator==(sparse_optional<T> const& cmp) const
124{
125 if (!v_ && !cmp.v_) {
126 return true;
127 }
128
129 if (!v_ || !cmp.v_) {
130 return false;
131 }
132
133 return *v_ == *cmp.v_;
134}
135
136template<typename T>
137bool sparse_optional<T>::operator<(sparse_optional<T> const& cmp) const
138{
139 if (!v_ || !cmp.v_) {
140 return cmp.v_ != nullptr;
141 }
142
143 return *v_ < *cmp.v_;
144}
145
146}
147
148#endif
Similar to C++17's std::optional, but stores the data in dynamic memory.
Definition optional.hpp:20
The namespace used by libfilezilla.
Definition apply.hpp:17
bool dispatch(event_base const &ev, F &&f)
Dispatch for simple_event<> based events to simple functors.
Definition event_handler.hpp:199