5
* Nullable values for C++
7
* Copyright 2004, 2007 MenTaLguY <mental@rydia.net>
9
* This code is licensed under the GNU GPL; see COPYING for more information.
22
class IsNothing : public std::domain_error {
24
IsNothing() : domain_error(std::string("Is nothing")) {}
32
MaybeStorage() : _is_nothing(true) {}
33
MaybeStorage(T const &value)
34
: _value(value), _is_nothing(false) {}
36
bool is_nothing() const { return _is_nothing; }
37
T &value() { return _value; }
38
T const &value() const { return _value; }
50
Maybe(T const &t) : _storage(t) {}
51
Maybe(Maybe const &m) : _storage(m._storage) {}
53
template <typename T2>
54
Maybe(Maybe<T2> const &m) {
60
template <typename T2>
61
Maybe(Maybe<T2 const &> m) {
67
operator bool() const { return !_storage.is_nothing(); }
69
T const &operator*() const throw(IsNothing) {
70
if (_storage.is_nothing()) {
73
return _storage.value();
76
T &operator*() throw(IsNothing) {
77
if (_storage.is_nothing()) {
80
return _storage.value();
84
T const *operator->() const throw(IsNothing) {
85
if (_storage.is_nothing()) {
88
return &_storage.value();
91
T *operator->() throw(IsNothing) {
92
if (_storage.is_nothing()) {
95
return &_storage.value();
99
template <typename T2>
100
bool operator==(Maybe<T2> const &other) const {
101
bool is_nothing = _storage.is_nothing();
102
if ( is_nothing || !other ) {
103
return is_nothing && !other;
105
return _storage.value() == *other;
108
template <typename T2>
109
bool operator!=(Maybe<T2> const &other) const {
110
bool is_nothing = _storage.is_nothing();
111
if ( is_nothing || !other ) {
112
return !is_nothing || other;
114
return _storage.value() != *other;
119
MaybeStorage<T> _storage;
122
template <typename T>
125
Maybe() : _ref(NULL) {}
126
Maybe(Nothing) : _ref(NULL) {}
127
Maybe(T &t) : _ref(&t) {}
129
template <typename T2>
130
Maybe(Maybe<T2> const &m) {
136
template <typename T2>
137
Maybe(Maybe<T2 &> m) {
143
template <typename T2>
144
Maybe(Maybe<T2 const &> m) {
150
operator bool() const { return _ref; }
152
T &operator*() const throw(IsNothing) {
159
T *operator->() const throw(IsNothing) {
167
template <typename T2>
168
bool operator==(Maybe<T2> const &other) const {
169
if ( !_ref || !other ) {
170
return !_ref && !other;
172
return *_ref == *other;
175
template <typename T2>
176
bool operator!=(Maybe <T2> const &other) const {
177
if ( !_ref || !other ) {
178
return _ref || other;
180
return *_ref != *other;
195
c-file-style:"stroustrup"
196
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
201
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :