1// Copyright (C) 2020 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
4#ifndef QVARIANT_H
5#define QVARIANT_H
6
7#include <QtCore/qatomic.h>
8#include <QtCore/qcontainerfwd.h>
9#include <QtCore/qmetatype.h>
10#ifndef QT_NO_DEBUG_STREAM
11#include <QtCore/qdebug.h>
12#endif
13
14#include <memory>
15#include <QtCore/q20type_traits.h>
16#include <QtCore/q23utility.h>
17#include <variant>
18
19#if !defined(QT_LEAN_HEADERS) || QT_LEAN_HEADERS < 1
20# include <QtCore/qlist.h>
21# include <QtCore/qstringlist.h>
22# include <QtCore/qbytearraylist.h>
23# include <QtCore/qhash.h>
24# include <QtCore/qmap.h>
25# include <QtCore/qobject.h>
26#endif
27
28QT_BEGIN_NAMESPACE
29
30QT_ENABLE_P0846_SEMANTICS_FOR(get_if)
31QT_ENABLE_P0846_SEMANTICS_FOR(get)
32
33class QBitArray;
34class QDataStream;
35class QDate;
36class QDateTime;
37class QEasingCurve;
38class QLine;
39class QLineF;
40class QLocale;
41class QModelIndex;
42class QPersistentModelIndex;
43class QPoint;
44class QPointF;
45class QRect;
46class QRectF;
47class QRegularExpression;
48class QSize;
49class QSizeF;
50class QTextFormat;
51class QTextLength;
52class QTime;
53class QTransform;
54class QUrl;
55class QVariant;
56
57template<typename T>
58inline T qvariant_cast(const QVariant &);
59
60namespace QtPrivate {
61template<> constexpr inline bool qIsRelocatable<QVariant> = true;
62}
63class Q_CORE_EXPORT QVariant
64{
65 template <typename T, typename... Args>
66 using if_constructible = std::enable_if_t<
67 std::conjunction_v<
68 std::is_copy_constructible<q20::remove_cvref_t<T>>,
69 std::is_destructible<q20::remove_cvref_t<T>>,
70 std::is_constructible<q20::remove_cvref_t<T>, Args...>
71 >,
72 bool>;
73
74 template <typename T>
75 using if_rvalue = std::enable_if_t<!std::is_reference_v<T>, bool>;
76
77 struct CborValueStandIn { qint64 n; void *c; int t; };
78public:
79 struct PrivateShared
80 {
81 private:
82 inline PrivateShared() : ref(1) { }
83 public:
84 static int computeOffset(PrivateShared *ps, size_t align);
85 static size_t computeAllocationSize(size_t size, size_t align);
86 static PrivateShared *create(size_t size, size_t align);
87 static void free(PrivateShared *p);
88
89 alignas(8) QAtomicInt ref;
90 int offset;
91
92 const void *data() const { return reinterpret_cast<const uchar *>(this) + offset; }
93 void *data() { return reinterpret_cast<uchar *>(this) + offset; }
94 };
95
96 struct Private
97 {
98 static constexpr size_t MaxInternalSize = 3 * sizeof(void *);
99 template <size_t S> static constexpr bool FitsInInternalSize = S <= MaxInternalSize;
100 template<typename T> static constexpr bool CanUseInternalSpace =
101 (QTypeInfo<T>::isRelocatable && FitsInInternalSize<sizeof(T)> && alignof(T) <= alignof(double));
102 static constexpr bool canUseInternalSpace(const QtPrivate::QMetaTypeInterface *type)
103 {
104 Q_ASSERT(type);
105 return QMetaType::TypeFlags(type->flags) & QMetaType::RelocatableType &&
106 size_t(type->size) <= MaxInternalSize && size_t(type->alignment) <= alignof(double);
107 }
108
109 union
110 {
111 uchar data[MaxInternalSize] = {};
112 PrivateShared *shared;
113 double _forAlignment; // we want an 8byte alignment on 32bit systems as well
114 } data;
115 quintptr is_shared : 1;
116 quintptr is_null : 1;
117 quintptr packedType : sizeof(QMetaType) * 8 - 2;
118
119 constexpr Private() noexcept : is_shared(false), is_null(true), packedType(0) {}
120 explicit Private(const QtPrivate::QMetaTypeInterface *iface) noexcept;
121 template <typename T> explicit Private(std::piecewise_construct_t, const T &t);
122
123 const void *storage() const
124 { return is_shared ? data.shared->data() : &data.data; }
125
126 // determine internal storage at compile time
127 template<typename T> const T &get() const
128 { return *static_cast<const T *>(CanUseInternalSpace<T> ? &data.data : data.shared->data()); }
129
130 inline const QtPrivate::QMetaTypeInterface *typeInterface() const
131 {
132 return reinterpret_cast<const QtPrivate::QMetaTypeInterface *>(packedType << 2);
133 }
134
135 inline QMetaType type() const
136 {
137 return QMetaType(typeInterface());
138 }
139 };
140
141#if QT_DEPRECATED_SINCE(6, 0)
142 enum QT_DEPRECATED_VERSION_X_6_0("Use QMetaType::Type instead.") Type
143 {
144 Invalid = QMetaType::UnknownType,
145 Bool = QMetaType::Bool,
146 Int = QMetaType::Int,
147 UInt = QMetaType::UInt,
148 LongLong = QMetaType::LongLong,
149 ULongLong = QMetaType::ULongLong,
150 Double = QMetaType::Double,
151 Char = QMetaType::QChar,
152 Map = QMetaType::QVariantMap,
153 List = QMetaType::QVariantList,
154 String = QMetaType::QString,
155 StringList = QMetaType::QStringList,
156 ByteArray = QMetaType::QByteArray,
157 BitArray = QMetaType::QBitArray,
158 Date = QMetaType::QDate,
159 Time = QMetaType::QTime,
160 DateTime = QMetaType::QDateTime,
161 Url = QMetaType::QUrl,
162 Locale = QMetaType::QLocale,
163 Rect = QMetaType::QRect,
164 RectF = QMetaType::QRectF,
165 Size = QMetaType::QSize,
166 SizeF = QMetaType::QSizeF,
167 Line = QMetaType::QLine,
168 LineF = QMetaType::QLineF,
169 Point = QMetaType::QPoint,
170 PointF = QMetaType::QPointF,
171#if QT_CONFIG(regularexpression)
172 RegularExpression = QMetaType::QRegularExpression,
173#endif
174 Hash = QMetaType::QVariantHash,
175#if QT_CONFIG(easingcurve)
176 EasingCurve = QMetaType::QEasingCurve,
177#endif
178 Uuid = QMetaType::QUuid,
179#if QT_CONFIG(itemmodel)
180 ModelIndex = QMetaType::QModelIndex,
181 PersistentModelIndex = QMetaType::QPersistentModelIndex,
182#endif
183 LastCoreType = QMetaType::LastCoreType,
184
185 Font = QMetaType::QFont,
186 Pixmap = QMetaType::QPixmap,
187 Brush = QMetaType::QBrush,
188 Color = QMetaType::QColor,
189 Palette = QMetaType::QPalette,
190 Image = QMetaType::QImage,
191 Polygon = QMetaType::QPolygon,
192 Region = QMetaType::QRegion,
193 Bitmap = QMetaType::QBitmap,
194 Cursor = QMetaType::QCursor,
195#if QT_CONFIG(shortcut)
196 KeySequence = QMetaType::QKeySequence,
197#endif
198 Pen = QMetaType::QPen,
199 TextLength = QMetaType::QTextLength,
200 TextFormat = QMetaType::QTextFormat,
201 Transform = QMetaType::QTransform,
202 Matrix4x4 = QMetaType::QMatrix4x4,
203 Vector2D = QMetaType::QVector2D,
204 Vector3D = QMetaType::QVector3D,
205 Vector4D = QMetaType::QVector4D,
206 Quaternion = QMetaType::QQuaternion,
207 PolygonF = QMetaType::QPolygonF,
208 Icon = QMetaType::QIcon,
209 LastGuiType = QMetaType::LastGuiType,
210
211 SizePolicy = QMetaType::QSizePolicy,
212
213 UserType = QMetaType::User,
214 LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type
215 };
216#endif
217 QVariant() noexcept : d() {}
218 ~QVariant();
219 explicit QVariant(QMetaType type, const void *copy = nullptr);
220 QVariant(const QVariant &other);
221
222private:
223 template <typename T, typename ...Args>
224 using is_noexcept_constructible = std::conjunction<
225 std::bool_constant<Private::CanUseInternalSpace<T>>,
226 std::is_nothrow_constructible<T, Args...>
227 >;
228
229public:
230 template <typename T, typename... Args,
231 if_constructible<T, Args...> = true>
232 explicit QVariant(std::in_place_type_t<T>, Args&&... args)
233 noexcept(is_noexcept_constructible<q20::remove_cvref_t<T>, Args...>::value)
234 : QVariant(std::in_place, QMetaType::fromType<q20::remove_cvref_t<T>>() )
235 {
236 void *data = const_cast<void *>(constData());
237 new (data) T(std::forward<Args>(args)...);
238 }
239
240 template <typename T, typename U, typename... Args,
241 if_constructible<T, std::initializer_list<U> &, Args...> = true>
242 explicit QVariant(std::in_place_type_t<T>, std::initializer_list<U> il, Args&&... args)
243 noexcept(is_noexcept_constructible<q20::remove_cvref_t<T>,
244 std::initializer_list<U> &,
245 Args...
246 >::value)
247 : QVariant(std::in_place, QMetaType::fromType<q20::remove_cvref_t<T>>())
248 {
249 char *data = static_cast<char *>(const_cast<void *>(constData()));
250 new (data) T(il, std::forward<Args>(args)...);
251 }
252
253 // primitives
254 QVariant(int i) noexcept;
255 QVariant(uint ui) noexcept;
256 QVariant(qlonglong ll) noexcept;
257 QVariant(qulonglong ull) noexcept;
258 QVariant(bool b) noexcept;
259 QVariant(double d) noexcept;
260 QVariant(float f) noexcept;
261
262 // trivial, trivially-copyable or COW
263 QVariant(QChar qchar) noexcept;
264 QVariant(QDate date) noexcept;
265 QVariant(QTime time) noexcept;
266 QVariant(const QBitArray &bitarray) noexcept;
267 QVariant(const QByteArray &bytearray) noexcept;
268 QVariant(const QDateTime &datetime) noexcept;
269 QVariant(const QHash<QString, QVariant> &hash) noexcept;
270 QVariant(const QJsonArray &jsonArray) noexcept;
271 QVariant(const QJsonObject &jsonObject) noexcept;
272 QVariant(const QList<QVariant> &list) noexcept;
273 QVariant(const QLocale &locale) noexcept;
274 QVariant(const QMap<QString, QVariant> &map) noexcept;
275 QVariant(const QRegularExpression &re) noexcept;
276 QVariant(const QString &string) noexcept;
277 QVariant(const QStringList &stringlist) noexcept;
278 QVariant(const QUrl &url) noexcept;
279
280 // conditionally noexcept trivial or trivially-copyable
281 // (most of these are noexcept on 64-bit)
282 QVariant(const QJsonValue &jsonValue) noexcept(Private::FitsInInternalSize<sizeof(CborValueStandIn)>);
283 QVariant(const QModelIndex &modelIndex) noexcept(Private::FitsInInternalSize<8 + 2 * sizeof(quintptr)>);
284 QVariant(QUuid uuid) noexcept(Private::FitsInInternalSize<16>);
285#ifndef QT_NO_GEOM_VARIANT
286 QVariant(QSize size) noexcept;
287 QVariant(QSizeF size) noexcept(Private::FitsInInternalSize<sizeof(qreal) * 2>);
288 QVariant(QPoint pt) noexcept;
289 QVariant(QPointF pt) noexcept(Private::FitsInInternalSize<sizeof(qreal) * 2>);
290 QVariant(QLine line) noexcept(Private::FitsInInternalSize<sizeof(int) * 4>);
291 QVariant(QLineF line) noexcept(Private::FitsInInternalSize<sizeof(qreal) * 4>);
292 QVariant(QRect rect) noexcept(Private::FitsInInternalSize<sizeof(int) * 4>);
293 QVariant(QRectF rect) noexcept(Private::FitsInInternalSize<sizeof(qreal) * 4>);
294#endif
295
296 // not noexcept
297 QVariant(const QEasingCurve &easing) noexcept(false);
298 QVariant(const QJsonDocument &jsonDocument) noexcept(false);
299 QVariant(const QPersistentModelIndex &modelIndex) noexcept(false);
300
301#ifndef QT_NO_CAST_FROM_ASCII
302 QT_ASCII_CAST_WARN QVariant(const char *str) noexcept(false)
303 : QVariant(QString::fromUtf8(utf8: str))
304 {}
305#endif
306 QVariant(QLatin1StringView string) noexcept(false); // converts to QString
307
308#if !defined(Q_CC_GHS)
309 // GHS has an ICE with this code; use the simplified version below
310 template <typename T,
311 std::enable_if_t<std::disjunction_v<std::is_pointer<T>, std::is_member_pointer<T>>, bool> = false>
312 QVariant(T) = delete;
313#else
314 QVariant(const volatile void *) = delete;
315#endif
316
317#if QT_CORE_REMOVED_SINCE(6, 5)
318 QVariant(const QSize &size);
319 QVariant(const QSizeF &size);
320 QVariant(const QPoint &pt);
321 QVariant(const QPointF &pt);
322 QVariant(const QLine &line);
323 QVariant(const QLineF &line);
324 QVariant(const QRect &rect);
325 QVariant(const QRectF &rect);
326 QVariant(const QUuid &uuid);
327#endif
328
329 QVariant& operator=(const QVariant &other);
330 inline QVariant(QVariant &&other) noexcept : d(other.d)
331 { other.d = Private(); }
332 QT_MOVE_ASSIGNMENT_OPERATOR_IMPL_VIA_MOVE_AND_SWAP(QVariant)
333
334 inline void swap(QVariant &other) noexcept { std::swap(a&: d, b&: other.d); }
335
336 int userType() const { return typeId(); }
337 int typeId() const { return metaType().id(); }
338
339 const char *typeName() const;
340 QMetaType metaType() const;
341
342 bool canConvert(QMetaType targetType) const
343 { return QMetaType::canConvert(fromType: d.type(), toType: targetType); }
344 bool convert(QMetaType type);
345
346 bool canView(QMetaType targetType) const
347 { return QMetaType::canView(fromType: d.type(), toType: targetType); }
348
349#if QT_DEPRECATED_SINCE(6, 0)
350 QT_DEPRECATED_VERSION_6_0
351 bool canConvert(int targetTypeId) const
352 { return QMetaType::canConvert(fromType: d.type(), toType: QMetaType(targetTypeId)); }
353 QT_DEPRECATED_VERSION_6_0
354 bool convert(int targetTypeId)
355 { return convert(type: QMetaType(targetTypeId)); }
356#endif
357
358 inline bool isValid() const;
359 bool isNull() const;
360
361 void clear();
362
363 void detach();
364 inline bool isDetached() const;
365
366 int toInt(bool *ok = nullptr) const;
367 uint toUInt(bool *ok = nullptr) const;
368 qlonglong toLongLong(bool *ok = nullptr) const;
369 qulonglong toULongLong(bool *ok = nullptr) const;
370 bool toBool() const;
371 double toDouble(bool *ok = nullptr) const;
372 float toFloat(bool *ok = nullptr) const;
373 qreal toReal(bool *ok = nullptr) const;
374 QByteArray toByteArray() const;
375 QBitArray toBitArray() const;
376 QString toString() const;
377 QStringList toStringList() const;
378 QChar toChar() const;
379 QDate toDate() const;
380 QTime toTime() const;
381 QDateTime toDateTime() const;
382 QList<QVariant> toList() const;
383 QMap<QString, QVariant> toMap() const;
384 QHash<QString, QVariant> toHash() const;
385
386#ifndef QT_NO_GEOM_VARIANT
387 QPoint toPoint() const;
388 QPointF toPointF() const;
389 QRect toRect() const;
390 QSize toSize() const;
391 QSizeF toSizeF() const;
392 QLine toLine() const;
393 QLineF toLineF() const;
394 QRectF toRectF() const;
395#endif
396 QLocale toLocale() const;
397#if QT_CONFIG(regularexpression)
398 QRegularExpression toRegularExpression() const;
399#endif // QT_CONFIG(regularexpression)
400#if QT_CONFIG(easingcurve)
401 QEasingCurve toEasingCurve() const;
402#endif
403 QUuid toUuid() const;
404#ifndef QT_BOOTSTRAPPED
405 QUrl toUrl() const;
406 QJsonValue toJsonValue() const;
407 QJsonObject toJsonObject() const;
408 QJsonArray toJsonArray() const;
409 QJsonDocument toJsonDocument() const;
410#endif // QT_BOOTSTRAPPED
411#if QT_CONFIG(itemmodel)
412 QModelIndex toModelIndex() const;
413 QPersistentModelIndex toPersistentModelIndex() const;
414#endif
415
416#ifndef QT_NO_DATASTREAM
417 void load(QDataStream &ds);
418 void save(QDataStream &ds) const;
419#endif
420#if QT_DEPRECATED_SINCE(6, 0)
421 QT_WARNING_PUSH
422 QT_WARNING_DISABLE_DEPRECATED
423 QT_DEPRECATED_VERSION_X_6_0("Use the constructor taking a QMetaType instead.")
424 explicit QVariant(Type type)
425 : QVariant(QMetaType(int(type)))
426 {}
427 QT_DEPRECATED_VERSION_X_6_0("Use typeId() or metaType().")
428 Type type() const
429 {
430 int type = d.type().id();
431 return type >= QMetaType::User ? UserType : static_cast<Type>(type);
432 }
433 QT_DEPRECATED_VERSION_6_0
434 static const char *typeToName(int typeId)
435 { return QMetaType(typeId).name(); }
436 QT_DEPRECATED_VERSION_6_0
437 static Type nameToType(const char *name)
438 {
439 int metaType = QMetaType::fromName(name).id();
440 return metaType <= int(UserType) ? QVariant::Type(metaType) : UserType;
441 }
442 QT_WARNING_POP
443#endif
444
445 void *data();
446 const void *constData() const
447 { return d.storage(); }
448 inline const void *data() const { return constData(); }
449
450private:
451 template <typename T>
452 void verifySuitableForEmplace()
453 {
454 static_assert(!std::is_reference_v<T>,
455 "QVariant does not support reference types");
456 static_assert(!std::is_const_v<T>,
457 "QVariant does not support const types");
458 static_assert(std::is_copy_constructible_v<T>,
459 "QVariant requires that the type is copyable");
460 static_assert(std::is_destructible_v<T>,
461 "QVariant requires that the type is destructible");
462 }
463
464 template <typename T, typename... Args>
465 T &emplaceImpl(Args&&... args)
466 {
467 verifySuitableForEmplace<T>();
468 auto data = static_cast<T *>(prepareForEmplace(type: QMetaType::fromType<T>()));
469 return *q20::construct_at(data, std::forward<Args>(args)...);
470 }
471
472public:
473 template <typename T, typename... Args,
474 if_constructible<T, Args...> = true>
475 T &emplace(Args&&... args)
476 {
477 return emplaceImpl<T>(std::forward<Args>(args)...);
478 }
479
480 template <typename T, typename U, typename... Args,
481 if_constructible<T, std::initializer_list<U> &, Args...> = true>
482 T &emplace(std::initializer_list<U> list, Args&&... args)
483 {
484 return emplaceImpl<T>(list, std::forward<Args>(args)...);
485 }
486
487 template<typename T, typename = std::enable_if_t<!std::is_same_v<std::decay_t<T>, QVariant>>>
488 void setValue(T &&avalue)
489 {
490 using VT = std::decay_t<T>;
491 QMetaType metaType = QMetaType::fromType<VT>();
492 // If possible we reuse the current QVariant private.
493 if (isDetached() && d.type() == metaType) {
494 *reinterpret_cast<VT *>(const_cast<void *>(constData())) = std::forward<T>(avalue);
495 } else {
496 *this = QVariant::fromValue<VT>(std::forward<T>(avalue));
497 }
498 }
499
500 void setValue(const QVariant &avalue)
501 {
502 *this = avalue;
503 }
504
505 void setValue(QVariant &&avalue)
506 {
507 *this = std::move(avalue);
508 }
509
510 template<typename T>
511 inline T value() const
512 { return qvariant_cast<T>(*this); }
513
514 template<typename T>
515 inline T view()
516 {
517 T t{};
518 QMetaType::view(fromType: metaType(), from: data(), toType: QMetaType::fromType<T>(), to: &t);
519 return t;
520 }
521
522 template<typename T, if_rvalue<T> = true>
523#ifndef Q_QDOC
524 /* needs is_copy_constructible for variants semantics, is_move_constructible so that moveConstruct works
525 (but copy_constructible implies move_constructble, so don't bother checking)
526 */
527 static inline auto fromValue(T &&value)
528 noexcept(std::is_nothrow_copy_constructible_v<T> && Private::CanUseInternalSpace<T>)
529 -> std::enable_if_t<std::conjunction_v<std::is_copy_constructible<T>,
530 std::is_destructible<T>>, QVariant>
531#else
532 static inline QVariant fromValue(T &&value)
533#endif
534 {
535 // handle special cases
536 using Type = std::remove_cv_t<T>;
537 if constexpr (std::is_null_pointer_v<Type>)
538 return QVariant(QMetaType::fromType<std::nullptr_t>());
539 else if constexpr (std::is_same_v<Type, QVariant>)
540 return std::forward<T>(value);
541 else if constexpr (std::is_same_v<Type, std::monostate>)
542 return QVariant();
543 QMetaType mt = QMetaType::fromType<Type>();
544 mt.registerType(); // we want the type stored in QVariant to always be registered
545 // T is a forwarding reference, so if T satifies the enable-ifery,
546 // we get this overload even if T is an lvalue reference and thus must check here
547 // Moreover, we only try to move if the type is actually moveable and not if T is const
548 // as in const int i; QVariant::fromValue(std::move(i));
549 if constexpr (std::conjunction_v<std::is_move_constructible<Type>, std::negation<std::is_const<T>>>)
550 return moveConstruct(type: QMetaType::fromType<Type>(), data: std::addressof(value));
551 else
552 return copyConstruct(type: mt, data: std::addressof(value));
553 }
554
555 template<typename T>
556#ifndef Q_QDOC
557 static inline auto fromValue(const T &value)
558 noexcept(std::is_nothrow_copy_constructible_v<T> && Private::CanUseInternalSpace<T>)
559 -> std::enable_if_t<std::is_copy_constructible_v<T> && std::is_destructible_v<T>, QVariant>
560#else
561 static inline QVariant fromValue(const T &value)
562#endif
563 {
564 if constexpr (std::is_null_pointer_v<T>)
565 return QVariant(QMetaType::fromType<std::nullptr_t>());
566 else if constexpr (std::is_same_v<T, QVariant>)
567 return value;
568 else if constexpr (std::is_same_v<T, std::monostate>)
569 return QVariant();
570 return QVariant(QMetaType::fromType<T>(), std::addressof(value));
571 }
572
573 template<typename... Types>
574 static inline QVariant fromStdVariant(const std::variant<Types...> &value)
575 {
576 return fromStdVariantImpl(value);
577 }
578
579 template<typename... Types>
580 static QVariant fromStdVariant(std::variant<Types...> &&value)
581 {
582 return fromStdVariantImpl(std::move(value));
583 }
584
585 template<typename T>
586 bool canConvert() const
587 { return canConvert(QMetaType::fromType<T>()); }
588
589 template<typename T>
590 bool canView() const
591 { return canView(QMetaType::fromType<T>()); }
592
593 static QPartialOrdering compare(const QVariant &lhs, const QVariant &rhs);
594
595private:
596 template <typename StdVariant>
597 static QVariant fromStdVariantImpl(StdVariant &&v)
598 {
599 if (Q_UNLIKELY(v.valueless_by_exception()))
600 return QVariant();
601 auto visitor = [](auto &&arg) {
602 return QVariant::fromValue(q23::forward_like<StdVariant>(arg));
603 };
604 return std::visit(visitor, std::forward<StdVariant>(v));
605 }
606
607 friend inline bool operator==(const QVariant &a, const QVariant &b)
608 { return a.equals(other: b); }
609 friend inline bool operator!=(const QVariant &a, const QVariant &b)
610 { return !a.equals(other: b); }
611#ifndef QT_NO_DEBUG_STREAM
612 template <typename T>
613 friend auto operator<<(const QDebug &debug, const T &variant) -> std::enable_if_t<std::is_same_v<T, QVariant>, QDebug> {
614 return variant.qdebugHelper(debug);
615 }
616 QDebug qdebugHelper(QDebug) const;
617#endif
618
619 template <typename T>
620 friend T *get_if(QVariant *v) noexcept
621 {
622 // data() will detach from is_null, returning non-nullptr
623 if (!v || v->d.type() != QMetaType::fromType<T>())
624 return nullptr;
625 return static_cast<T*>(v->data());
626 }
627 template <typename T>
628 friend const T *get_if(const QVariant *v) noexcept
629 {
630 // (const) data() will not detach from is_null, return nullptr
631 if (!v || v->d.is_null || v->d.type() != QMetaType::fromType<T>())
632 return nullptr;
633 return static_cast<const T*>(v->data());
634 }
635
636#define Q_MK_GET(cvref) \
637 template <typename T> \
638 friend T cvref get(QVariant cvref v) \
639 { \
640 if constexpr (std::is_const_v<T cvref>) \
641 Q_ASSERT(!v.d.is_null); \
642 Q_ASSERT(v.d.type() == QMetaType::fromType<q20::remove_cvref_t<T>>()); \
643 return static_cast<T cvref>(*get_if<T>(&v)); \
644 } \
645 /* end */
646 Q_MK_GET(&)
647 Q_MK_GET(const &)
648 Q_MK_GET(&&)
649 Q_MK_GET(const &&)
650#undef Q_MK_GET
651
652 static QVariant moveConstruct(QMetaType type, void *data);
653 static QVariant copyConstruct(QMetaType type, const void *data);
654
655 template<typename T>
656 friend inline T qvariant_cast(const QVariant &);
657protected:
658 Private d;
659 void create(int type, const void *copy);
660 void create(QMetaType type, const void *copy);
661 bool equals(const QVariant &other) const;
662 bool convert(int type, void *ptr) const;
663 bool view(int type, void *ptr);
664
665private:
666 // force compile error, prevent QVariant(bool) to be called
667 inline QVariant(void *) = delete;
668 // QVariant::Type is marked as \obsolete, but we don't want to
669 // provide a constructor from its intended replacement,
670 // QMetaType::Type, instead, because the idea behind these
671 // constructors is flawed in the first place. But we also don't
672 // want QVariant(QMetaType::String) to compile and falsely be an
673 // int variant, so delete this constructor:
674 QVariant(QMetaType::Type) = delete;
675
676 // used to setup the QVariant internals for the "real" inplace ctor
677 QVariant(std::in_place_t, QMetaType type);
678 // helper for emplace
679 void *prepareForEmplace(QMetaType type);
680
681 // These constructors don't create QVariants of the type associated
682 // with the enum, as expected, but they would create a QVariant of
683 // type int with the value of the enum value.
684 // Use QVariant v = QColor(Qt::red) instead of QVariant v = Qt::red for
685 // example.
686 QVariant(Qt::GlobalColor) = delete;
687 QVariant(Qt::BrushStyle) = delete;
688 QVariant(Qt::PenStyle) = delete;
689 QVariant(Qt::CursorShape) = delete;
690#ifdef QT_NO_CAST_FROM_ASCII
691 // force compile error when implicit conversion is not wanted
692 inline QVariant(const char *) = delete;
693#endif
694public:
695 typedef Private DataPtr;
696 inline DataPtr &data_ptr() { return d; }
697 inline const DataPtr &data_ptr() const { return d; }
698};
699
700inline bool QVariant::isValid() const
701{
702 return d.type().isValid();
703}
704
705#ifndef QT_NO_DATASTREAM
706Q_CORE_EXPORT QDataStream &operator>>(QDataStream &s, QVariant &p);
707Q_CORE_EXPORT QDataStream &operator<<(QDataStream &s, const QVariant &p);
708
709#if QT_DEPRECATED_SINCE(6, 0)
710QT_WARNING_PUSH
711QT_WARNING_DISABLE_DEPRECATED
712QT_DEPRECATED_VERSION_6_0
713inline QDataStream &operator>>(QDataStream &s, QVariant::Type &p)
714{
715 quint32 u;
716 s >> u;
717 p = static_cast<QVariant::Type>(u);
718 return s;
719}
720QT_DEPRECATED_VERSION_6_0
721inline QDataStream &operator<<(QDataStream &s, const QVariant::Type p)
722{
723 s << static_cast<quint32>(p);
724 return s;
725}
726QT_WARNING_POP
727#endif
728
729#endif
730
731inline bool QVariant::isDetached() const
732{ return !d.is_shared || d.data.shared->ref.loadRelaxed() == 1; }
733
734inline void swap(QVariant &value1, QVariant &value2) noexcept
735{ value1.swap(other&: value2); }
736
737#ifndef QT_MOC
738
739template<typename T> inline T qvariant_cast(const QVariant &v)
740{
741 QMetaType targetType = QMetaType::fromType<T>();
742 if (v.d.type() == targetType)
743 return v.d.get<T>();
744 if constexpr (std::is_same_v<T,std::remove_const_t<std::remove_pointer_t<T>> const *>) {
745 using nonConstT = std::remove_const_t<std::remove_pointer_t<T>> *;
746 QMetaType nonConstTargetType = QMetaType::fromType<nonConstT>();
747 if (v.d.type() == nonConstTargetType)
748 return v.d.get<nonConstT>();
749 }
750
751 T t{};
752 QMetaType::convert(v.metaType(), v.constData(), targetType, &t);
753 return t;
754}
755
756template<> inline QVariant qvariant_cast<QVariant>(const QVariant &v)
757{
758 if (v.metaType().id() == QMetaType::QVariant)
759 return *reinterpret_cast<const QVariant *>(v.constData());
760 return v;
761}
762
763#endif
764
765#ifndef QT_NO_DEBUG_STREAM
766#if QT_DEPRECATED_SINCE(6, 0)
767QT_WARNING_PUSH
768QT_WARNING_DISABLE_DEPRECATED
769QT_DEPRECATED_VERSION_6_0
770Q_CORE_EXPORT QDebug operator<<(QDebug, const QVariant::Type);
771QT_WARNING_POP
772#endif
773#endif
774
775namespace QtPrivate {
776class Q_CORE_EXPORT QVariantTypeCoercer
777{
778public:
779 // ### Qt7: Pass QMetaType as value rather than const ref.
780 const void *convert(const QVariant &value, const QMetaType &type);
781 const void *coerce(const QVariant &value, const QMetaType &type);
782
783private:
784 QVariant converted;
785};
786}
787
788template<typename Pointer>
789class QVariantRef
790{
791private:
792 const Pointer *m_pointer = nullptr;
793
794public:
795 explicit QVariantRef(const Pointer *reference) : m_pointer(reference) {}
796 QVariantRef(const QVariantRef &) = default;
797 QVariantRef(QVariantRef &&) = default;
798 ~QVariantRef() = default;
799
800 operator QVariant() const;
801 QVariantRef &operator=(const QVariant &value);
802 QVariantRef &operator=(const QVariantRef &value) { return operator=(QVariant(value)); }
803 QVariantRef &operator=(QVariantRef &&value) { return operator=(QVariant(value)); }
804
805 friend void swap(QVariantRef a, QVariantRef b)
806 {
807 QVariant tmp = a;
808 a = b;
809 b = std::move(tmp);
810 }
811};
812
813class Q_CORE_EXPORT QVariantConstPointer
814{
815private:
816 QVariant m_variant;
817
818public:
819 explicit QVariantConstPointer(QVariant variant);
820
821 QVariant operator*() const;
822 const QVariant *operator->() const;
823};
824
825template<typename Pointer>
826class QVariantPointer
827{
828private:
829 const Pointer *m_pointer = nullptr;
830
831public:
832 explicit QVariantPointer(const Pointer *pointer) : m_pointer(pointer) {}
833 QVariantRef<Pointer> operator*() const { return QVariantRef<Pointer>(m_pointer); }
834 Pointer operator->() const { return *m_pointer; }
835};
836
837QT_END_NAMESPACE
838
839#endif // QVARIANT_H
840

source code of qtbase/src/corelib/kernel/qvariant.h