Rise
The Vieneo Province
Nullable.h
Go to the documentation of this file.
1 
3 #pragma once
4 
5 #include <stdexcept>
6 
7 template <typename T>
8 class Nullable
9 {
11  bool m_isSet;
12 
13  void set(T value)
14  {
15  m_value = value;
16  m_isSet = true;
17  }
18 
19 public:
20  Nullable() : m_value(), m_isSet(false)
21  {
22  }
23 
24  Nullable(T value) : m_value(value), m_isSet(true)
25  {
26  }
27 
28  Nullable(const Nullable& other) : m_value(other.m_value), m_isSet(other.m_isSet)
29  {
30  }
31 
32  // Used in copy-constructor below, see comment on copy constructor
33  /*friend void swap(Nullable& a, Nullable& b)
34  {
35  std::swap(a.m_isSet, b.m_isSet);
36  std::swap(a.m_value, b.m_value);
37  }
38 
40  Nullable& operator=(Nullable other)
41  {
42  swap(*this, other);
43  return *this;
44  }*/
45 
46  T operator=(T value)
47  {
48  set(value);
49  return m_value;
50  }
51 
52  bool operator==(const T value)
53  {
54  return m_isSet && value == m_value;
55  }
56 
57  bool operator==(const Nullable& other)
58  {
59  if (other.is_set() != m_isSet ||
60  (other.is_set() && m_isSet && other.get() != m_value))
61  return false;
62 
63  return true;
64  }
65 
66  bool operator!=(const Nullable& other)
67  {
68  if (other.is_set() != m_isSet ||
69  (other.is_set() && m_isSet && other.get() != m_value))
70  return true;
71 
72  return false;
73  }
74 
75  operator T() const
76  {
77  return get();
78  }
79 
80  T get() const
81  {
82  if (m_isSet) return m_value;
83 
84  throw std::logic_error("Value of Nullable is not set.");
85  }
86 
87  bool is_set() const
88  {
89  return m_isSet;
90  }
91 
92  void reset()
93  {
94  m_isSet = false;
95  }
96 };
Nullable(T value)
Definition: Nullable.h:24
Nullable(const Nullable &other)
Definition: Nullable.h:28
T operator=(T value)
Definition: Nullable.h:46
bool operator!=(const Nullable &other)
Definition: Nullable.h:66
Nullable()
Definition: Nullable.h:20
void reset()
Definition: Nullable.h:92
bool operator==(const Nullable &other)
Definition: Nullable.h:57
T m_value
Definition: Nullable.h:10
bool is_set() const
Definition: Nullable.h:87
bool operator==(const T value)
Definition: Nullable.h:52
bool m_isSet
Definition: Nullable.h:11
T get() const
Definition: Nullable.h:80