KCGroups

optional.h
1 // SPDX-FileCopyrightText: 2020 Henri Chain <[email protected]>
2 // SPDX-FileCopyrightText: 2020 Kevin Ottens <[email protected]>
3 //
4 // SPDX-License-Identifier: LGPL-2.1-or-later
5 
6 #ifndef OPTIONAL_H
7 #define OPTIONAL_H
8 
9 #include <memory>
10 #include <type_traits>
11 
12 namespace KCGroups
13 {
14 template<typename T>
15 class optional
16 {
17  static_assert(!std::is_reference<T>::value, "optional doesn't support references");
18 
19 public:
20  optional() = default;
21 
22  optional(const T &v)
23  : m_value(v)
24  , m_hasValue(true)
25  {
26  }
27 
28  optional(T &&v)
29  : m_value(std::move(v))
30  , m_hasValue(true)
31  {
32  }
33 
34  explicit operator bool() const noexcept
35  {
36  return m_hasValue;
37  }
38 
39  T const &operator*() const noexcept
40  {
41  return m_value;
42  }
43 
44  T operator*()
45  {
46  return m_value;
47  }
48 
49  optional &operator=(const T &v) noexcept
50  {
51  m_hasValue = true;
52  m_value = v;
53  return *this;
54  }
55 
56  optional &operator=(T &&v) noexcept
57  {
58  m_hasValue = true;
59  m_value = std::move(v);
60  return *this;
61  }
62 
63  void reset()
64  {
65  if (m_hasValue) {
66  m_value.~T();
67  m_hasValue = false;
68  }
69  }
70 
71 private:
72  T m_value = {};
73  bool m_hasValue = false;
74 }; // class optional
75 
76 template<typename T, typename U>
77 bool operator==(const optional<T> &lhs, const optional<U> &rhs) noexcept
78 {
79  const auto l = static_cast<bool>(lhs), r = static_cast<bool>(rhs);
80  return l && r ? *lhs == *rhs : !l && !r;
81 }
82 
83 template<typename T, typename U>
84 bool operator!=(const optional<T> &lhs, const optional<U> &rhs) noexcept
85 {
86  return !(lhs == rhs);
87 }
88 
89 template<typename T, typename U>
90 bool operator==(const optional<T> &lhs, const U &rhs) noexcept
91 {
92  return static_cast<bool>(lhs) && *lhs == rhs;
93 }
94 
95 template<typename T, typename U>
96 bool operator!=(const optional<T> &lhs, const U &rhs) noexcept
97 {
98  return !(lhs == rhs);
99 }
100 
101 template<typename T, typename U>
102 bool operator==(const T &lhs, const optional<T> &rhs) noexcept
103 {
104  return rhs == lhs;
105 }
106 
107 template<typename T, typename U>
108 bool operator!=(const T &lhs, const optional<T> &rhs) noexcept
109 {
110  return !(lhs == rhs);
111 }
112 }
113 #endif // OPTIONAL_H
bool operator==(const Qt3DRender::QGraphicsApiFilter &reference, const Qt3DRender::QGraphicsApiFilter &sample)
bool operator!=(const Qt3DRender::QGraphicsApiFilter &reference, const Qt3DRender::QGraphicsApiFilter &sample)
KIOCORE_EXPORT CopyJob * move(const QList< QUrl > &src, const QUrl &dest, JobFlags flags=DefaultFlags)
KGuiItem reset()
This file is part of the KDE documentation.
Documentation copyright © 1996-2023 The KDE developers.
Generated on Fri Dec 1 2023 04:13:56 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.