-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoptional.h
More file actions
68 lines (55 loc) · 1.01 KB
/
optional.h
File metadata and controls
68 lines (55 loc) · 1.01 KB
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
#ifndef OPTIONAL_H
#define OPTIONAL_H
#include <memory>
template<typename T>
class Optional
{
public:
Optional() :
_value(),
_hasValue(false)
{ }
Optional(const T& value) :
_value(value),
_hasValue(true)
{ }
Optional(T&& value) :
_value(std::move(value)),
_hasValue(true)
{ }
Optional<T>& operator=(const T& value)
{
_value = value;
_hasValue = true;
return *this;
}
Optional<T>& operator=(T&& value)
{
_value = std::move(value);
_hasValue = true;
return *this;
}
T& Value() { return _value; }
const T& Value() const { return _value; }
T& operator*() { return _value; }
const T& operator*() const { return _value; }
T* operator->() { return &_value; }
const T* operator->() const { return &_value; }
T& ValueOr(T& alt) {
if(_hasValue)
return Value();
else
return alt;
}
const T& ValueOr(const T& alt) const {
if(_hasValue)
return Value();
else
return alt;
}
bool HasValue() const { return _hasValue; }
private:
T _value;
bool _hasValue;
};
#endif