-
Notifications
You must be signed in to change notification settings - Fork 3
/
Optional.hpp
99 lines (81 loc) · 1.77 KB
/
Optional.hpp
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#pragma once
#include "Assert.hpp"
#include <type_traits>
#include <utility>
namespace Pvl {
struct OptionalNone {};
const OptionalNone NONE;
template <typename T>
class Optional {
typename std::aligned_storage<sizeof(T), alignof(T)>::type data_;
bool used_;
public:
Optional()
: used_(false) {}
Optional(OptionalNone)
: used_(false) {}
Optional(const T& value)
: used_(true) {
new (&data_) T(value);
}
Optional(T&& value)
: used_(true) {
new (&data_) T(std::move(value));
}
~Optional() {
if (used_) {
value().~T();
}
}
T& value() {
PVL_ASSERT(used_);
return reinterpret_cast<T&>(data_);
}
const T& value() const {
PVL_ASSERT(used_);
return reinterpret_cast<const T&>(data_);
}
template <typename Alt>
T valueOr(Alt&& alt) {
if (used_) {
return value();
} else {
return std::forward<Alt>(alt);
}
}
template <typename Exception, typename... TArgs>
T valueOrThrow(TArgs&&... args) {
if (used_) {
return value();
} else {
throw Exception(std::forward<TArgs>(args)...);
}
}
T* operator->() const {
PVL_ASSERT(used_);
return &value();
}
explicit operator bool() const {
return used_;
}
bool operator!() const {
return !used_;
}
};
template <typename T>
bool hasValue(const T&) {
return true;
}
template <typename T>
bool hasValue(const Optional<T>& opt) {
return bool(opt);
}
template <typename T>
const T& value(const T& v) {
return v;
}
template <typename T>
const T& value(const Optional<T>& opt) {
return opt.value();
}
} // namespace Pvl