-
Notifications
You must be signed in to change notification settings - Fork 0
/
optional.h
52 lines (45 loc) · 999 Bytes
/
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
#ifndef OPTIONAL_H
#define OPTIONAL_H
#include <string>
#include <type_traits>
#include <stdexcept>
template <typename T>
class optional {
public:
optional()
: _nothing(true) {};
optional(T val)
: _nothing(false)
, _val{val} {
}
bool is_nothing() const {
return _nothing;
}
T from_optional() const {
if (_nothing) {
throw std::runtime_error("Accessed empty optional");
}
return _val;
}
template <typename funcType>
auto operator>>=(funcType&& f) const {
if (!is_nothing()) {
return f(from_optional());
} else {
return decltype(f(std::declval<T>())) {};
}
}
std::string to_string() const {
if (_nothing) {
return "Nothing";
} else {
return "Just " + std::to_string(_val);
}
}
private:
bool _nothing = true;
union {
std::remove_reference_t<T> _val;
};
};
#endif