-
Notifications
You must be signed in to change notification settings - Fork 26
/
optional.h
82 lines (69 loc) · 2.03 KB
/
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
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
#pragma once
#include "optional_common.h"
#include <stdexcept>
#include <type_traits>
#if __cplusplus == 201103
#define WISE_ENUM_CONSTEXPR_14
#else
#define WISE_ENUM_CONSTEXPR_14 constexpr
#endif
namespace wise_enum {
/* A simple, *forward* compatible optional implementation. That is, it does not
* provide the full std::optional interface, but all the interface it does
* provide is found on std::optional, so it should not be a breaking change to
* upgrade to std::optional.
*/
template <class T>
class optional {
public:
static_assert(std::is_enum<T>::value,
"wise enum optional is only for enum types");
optional() = default;
optional(T t) : m_t(t), m_active(true) {}
WISE_ENUM_CONSTEXPR_14 T &operator*() & { return m_t; }
constexpr const T &operator*() const & { return m_t; }
WISE_ENUM_CONSTEXPR_14 T &&operator*() && { return m_t; }
constexpr const T &&operator*() const && { return m_t; }
constexpr explicit operator bool() const noexcept { return m_active; }
constexpr bool has_value() const noexcept { return m_active; }
WISE_ENUM_CONSTEXPR_14 T &value() & {
if (m_active)
return m_t;
else
WISE_ENUM_OPTIONAL_BAD_ACCESS;
}
WISE_ENUM_CONSTEXPR_14 const T &value() const & {
if (m_active)
return m_t;
else
WISE_ENUM_OPTIONAL_BAD_ACCESS;
}
WISE_ENUM_CONSTEXPR_14 T &&value() && {
if (m_active)
return m_t;
else
WISE_ENUM_OPTIONAL_BAD_ACCESS;
}
WISE_ENUM_CONSTEXPR_14 const T &&value() const && {
if (m_active)
return m_t;
else
WISE_ENUM_OPTIONAL_BAD_ACCESS;
}
template <class U>
WISE_ENUM_CONSTEXPR_14 T value_or(U &&u) {
if (m_active)
return m_t;
else
return std::forward<U>(u);
}
void reset() noexcept { m_active = false; }
optional(const optional &other) = default;
optional(optional &&other) = default;
optional &operator=(const optional &other) = default;
optional &operator=(optional &&other) = default;
private:
T m_t;
bool m_active = false;
};
} // namespace wise_enum