OpenLibrary
optional.hpp
1 /*
2  * Container for optional data.
3  * Copyright (C) 2014 MichaƂ Walenciak <MichalWalenciak@gmail.com>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  */
19 
20 #ifndef OPENLIBRARY_UTILS_OPTIONAL_HPP
21 #define OPENLIBRARY_UTILS_OPTIONAL_HPP
22 
23 namespace ol
24 {
25 
26  template<typename T>
27  class Optional
28  {
29  public:
30  Optional(): m_data(), m_present(false) {}
31  Optional(const Optional<T>& other): m_data(other.m_data), m_present(other.m_present) {}
32  Optional(const T& data): m_data(data), m_present(true) {}
33  Optional(Optional<T>&& other): m_data(std::move(other.m_data)), m_present(other.m_present) {}
34 
35  Optional<T>& operator=(const Optional<T>& other)
36  {
37  m_data = other.m_data;
38  m_present = other.m_present;
39 
40  return *this;
41  }
42 
43  Optional<T>& operator=(const T& data)
44  {
45  m_data = data;
46  m_present = true;
47 
48  return *this;
49  }
50 
51  Optional<T>& operator=(T&& data)
52  {
53  m_data = std::move(data);
54  m_present = true;
55 
56  return *this;
57  }
58 
59  const T* operator->() const
60  {
61  return &m_data;
62  }
63 
64  T* operator->()
65  {
66  return &m_data;
67  }
68 
69  const T& operator*() const
70  {
71  return m_data;
72  }
73 
74  T& operator*()
75  {
76  return m_data;
77  }
78 
79  bool operator!() const
80  {
81  return !m_present;
82  }
83 
84  operator bool() const
85  {
86  return m_present;
87  }
88 
89  bool is_initialized() const
90  {
91  return m_present;
92  }
93 
94  private:
95  T m_data;
96  bool m_present;
97  };
98 
99 }
100 
101 #endif // OPENLIBRARY_UTILS_OPTIONAL_HPP
Definition: optional.hpp:27
Definition: debug.hpp:45