Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtclasshelper_p.h
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#ifndef QTCLASSHELPER_P_H
6#define QTCLASSHELPER_P_H
7
8#include <QtCore/private/qglobal_p.h>
9
10//
11// W A R N I N G
12// -------------
13//
14// This file is not part of the Qt API. It exists purely as an
15// implementation detail. This header file may change from version to
16// version without notice, or even be removed.
17//
18// We mean it.
19//
20
21#include <type_traits>
22#include <utility>
23
24QT_BEGIN_NAMESPACE
25
26/*
27 Helper for setters overloaded on lvalue/rvalue. If the setter is doing a
28 lot of work around the actual assignment, a common pattern is to create a
29 private helper method
30
31 void doSetFoo(const Foo &lvalue, Foo *rvalue);
32
33 and implement the two setters inline by calling that function:
34
35 void setFoo(const Foo &f) { doSetFoo(f, nullptr); }
36 void setFoo(Foo &&f) { doSetFoo(f, &f); }
37
38 Then, in doSetFoo(), when assigning the argument to the member, use this
39 function:
40
41 q_choose_assign(m_foo, lvalue, rvalue);
42
43 or, when appending to a container,
44
45 q_choose_append(m_container, lvalue, rvalue);
46
47 The functions mandate (in the C++ sense) that all arguments are the same
48 type, so they deduce each argument separately and then static_assert that
49 they're the same. If we need std::exchange()-like mixed types later, it's
50 easy to relax. For now, avoid being overly general.
51*/
52template <typename T, typename U, typename V>
53decltype(auto) q_choose_assign(T &var, const U &lvalue, V *rvalue)
54{
55 static_assert(std::is_same_v<T, U>, "all arguments must be of the same type");
56 static_assert(std::is_same_v<U, V>, "all arguments must be of the same type");
57 if (rvalue)
58 return var = std::move(*rvalue);
59 else
60 return var = lvalue;
61}
62
63template <typename Container, typename U, typename V>
64decltype(auto) q_choose_append(Container &c, const U &lvalue, V *rvalue)
65{
66 static_assert(std::is_same_v<typename Container::value_type, U>, "arguments must match container");
67 static_assert(std::is_same_v<U, V>, "all arguments must be of the same type");
68 if (rvalue)
69 c.push_back(std::move(*rvalue));
70 else
71 c.push_back(lvalue);
72 return c.back();
73}
74
75QT_END_NAMESPACE
76
77#endif // QTCLASSHELPER_P_H
decltype(auto) q_choose_append(Container &c, const U &lvalue, V *rvalue)