Mir
optional_value.h
Go to the documentation of this file.
1 /*
2  * Copyright © 2014 Canonical Ltd.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License version 2 or 3 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 #ifndef MIR_OPTIONAL_VALUE_H_
18 #define MIR_OPTIONAL_VALUE_H_
19 
20 #include "mir/fatal.h"
21 #include <utility>
22 
23 namespace mir
24 {
25 template<typename T>
27 {
28 public:
29  optional_value() = default;
30  optional_value(T const& value) : value_(value), is_set_{true} {}
31 
32  optional_value& operator=(T const& value)
33  {
34  value_ = value;
35  is_set_ = true;
36  return *this;
37  }
38 
39  bool is_set() const { return is_set_; }
40 
41  T const& value() const
42  {
43  die_if_unset();
44  return value_;
45  }
46 
47  T& value()
48  {
49  die_if_unset();
50  return value_;
51  }
52 
53  T&& consume()
54  {
55  die_if_unset();
56  is_set_ = false;
57  return std::move(value_);
58  }
59 
60  operator bool() const
61  {
62  return is_set();
63  }
64 
65 private:
66  void die_if_unset() const
67  {
68  if (!is_set())
69  {
70  (*fatal_error)("Accessing value of unset optional");
71  }
72  }
73 
74  T value_;
75  bool is_set_{false};
76 };
77 
78 
79 template<typename T>
80 inline bool operator == (optional_value<T> const& lhs, optional_value<T> const& rhs)
81 {
82  return lhs.is_set() == rhs.is_set() &&
83  (!lhs.is_set() || lhs.value() == rhs.value());
84 }
85 
86 template<typename T>
87 inline bool operator != (optional_value<T> const& lhs, optional_value<T> const& rhs)
88 {
89  return !(lhs == rhs);
90 }
91 
92 template<typename T>
93 inline bool operator == (optional_value<T> const& lhs, T const& rhs)
94 {
95  return lhs.is_set() && (lhs.value() == rhs);
96 }
97 
98 template<typename T>
99 inline bool operator != (optional_value<T> const& lhs, T const& rhs)
100 {
101  return !(lhs == rhs);
102 }
103 
104 template<typename T>
105 inline bool operator == (T const& lhs, optional_value<T> const& rhs)
106 {
107  return rhs == lhs;
108 }
109 
110 template<typename T>
111 inline bool operator != (T const& lhs, optional_value<T> const& rhs)
112 {
113  return rhs != lhs;
114 }
115 }
116 
117 #endif /* MIR_OPTIONAL_VALUE_H_ */

Copyright © 2012-2022 Canonical Ltd.
Generated on Tue Sep 13 03:20:30 UTC 2022
This documentation is licensed under the GPL version 2 or 3.