KCGroups

optional.h
1// SPDX-FileCopyrightText: 2020 Henri Chain <henri.chain@enioka.com>
2// SPDX-FileCopyrightText: 2020 Kevin Ottens <kevin.ottens@enioka.com>
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
12namespace KCGroups
13{
14template<typename T>
15class optional
16{
17 static_assert(!std::is_reference<T>::value, "optional doesn't support references");
18
19public:
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
71private:
72 T m_value = {};
73 bool m_hasValue = false;
74}; // class optional
75
76template<typename T, typename U>
77bool 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
83template<typename T, typename U>
84bool operator!=(const optional<T> &lhs, const optional<U> &rhs) noexcept
85{
86 return !(lhs == rhs);
87}
88
89template<typename T, typename U>
90bool operator==(const optional<T> &lhs, const U &rhs) noexcept
91{
92 return static_cast<bool>(lhs) && *lhs == rhs;
93}
94
95template<typename T, typename U>
96bool operator!=(const optional<T> &lhs, const U &rhs) noexcept
97{
98 return !(lhs == rhs);
99}
100
101template<typename T, typename U>
102bool operator==(const T &lhs, const optional<T> &rhs) noexcept
103{
104 return rhs == lhs;
105}
106
107template<typename T, typename U>
108bool operator!=(const T &lhs, const optional<T> &rhs) noexcept
109{
110 return !(lhs == rhs);
111}
112}
113#endif // OPTIONAL_H
KIOCORE_EXPORT CopyJob * move(const QList< QUrl > &src, const QUrl &dest, JobFlags flags=DefaultFlags)
KIOCORE_EXPORT bool operator!=(const UDSEntry &entry, const UDSEntry &other)
bool operator==(const StyleDelim &l, const StyleDelim &r)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Sat Dec 21 2024 17:00:52 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.