-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNullable.h
116 lines (90 loc) · 2.27 KB
/
Nullable.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright 2017, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Authors: Patrick Brosi <brosi@informatik.uni-freiburg.de>
#include <stdexcept>
#ifndef UTIL_NULLABLE_H_
#define UTIL_NULLABLE_H_
namespace util {
template<typename T>
class Nullable {
public:
Nullable()
: val(), null(true) {}
Nullable(T* valPointer)
: val(), null(true) {
if (valPointer) {
assign(*valPointer);
}
}
Nullable(const T& value)
: val(value), null(false) {}
Nullable(const Nullable& other)
: val(other.val), null(other.isNull()) {}
Nullable& operator=(const Nullable& other) {
if (!other.isNull()) val = other.get();
null = other.isNull();
return *this;
}
T operator=(const T& other) {
assign(other);
return val;
}
/**
* Passing through comparision operators
*/
bool operator==(const Nullable& other) const {
return (other.isNull() && isNull()) || other.get() == get();
}
bool operator!=(const Nullable& other) const {
return !(*this == other);
}
bool operator<(const Nullable& other) const {
return !other.isNull() && !isNull() && get() < other.get();
}
bool operator>(const Nullable& other) const {
return !(*this < other || *this == other);
}
bool operator<=(const Nullable& other) const {
return *this < other || *this == other;
}
bool operator>=(const Nullable& other) const {
return *this > other || *this == other;
}
bool operator==(const T& other) const {
return !isNull() && other == get();
}
bool operator!=(const T& other) const {
return !(*this == other);
}
bool operator<(const T& other) const {
return !isNull() && get() < other;
}
bool operator>(const T& other) const {
return !(*this < other || *this == other);
}
bool operator<=(const T& other) const {
return *this < other || *this == other;
}
bool operator>=(const T& other) const {
return *this > other || *this == other;
}
operator T() const {
return get();
}
bool isNull() const {
return null;
}
T get() const {
if (!isNull()) return val;
else throw std::runtime_error("Trying to retrieve value of NULL object.");
}
private:
void assign(T v) {
val = v;
null = false;
}
T val;
bool null;
};
}
#endif // UTIL_NULLABLE_H_