Allow getting a const pointer out of a variant containing pointer
Currently A a; QVariant::fromValue(&a).value<const A*>() == nullptr; Still casting non const to const is safe, and worked in Qt5. After this change A a; QVariant::fromValue(&a).value<const A*>() == &a; Change-Id: I257049d084c712b00a338a2943d379aa478e0981 Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
This commit is contained in:
parent
6c7ed4c013
commit
f69144471b
@ -53,6 +53,7 @@
|
|||||||
#include <QtCore/qbytearraylist.h>
|
#include <QtCore/qbytearraylist.h>
|
||||||
#endif
|
#endif
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
#if __has_include(<variant>) && __cplusplus >= 201703L
|
#if __has_include(<variant>) && __cplusplus >= 201703L
|
||||||
#include <variant>
|
#include <variant>
|
||||||
@ -572,6 +573,12 @@ template<typename T> inline T qvariant_cast(const QVariant &v)
|
|||||||
QMetaType targetType = QMetaType::fromType<T>();
|
QMetaType targetType = QMetaType::fromType<T>();
|
||||||
if (v.d.type() == targetType)
|
if (v.d.type() == targetType)
|
||||||
return v.d.get<T>();
|
return v.d.get<T>();
|
||||||
|
if constexpr (std::is_same_v<T,std::remove_const_t<std::remove_pointer_t<T>> const *>) {
|
||||||
|
using nonConstT = std::remove_const_t<std::remove_pointer_t<T>> *;
|
||||||
|
QMetaType nonConstTargetType = QMetaType::fromType<nonConstT>();
|
||||||
|
if (v.d.type() == nonConstTargetType)
|
||||||
|
return v.d.get<nonConstT>();
|
||||||
|
}
|
||||||
|
|
||||||
T t{};
|
T t{};
|
||||||
QMetaType::convert(v.metaType(), v.constData(), targetType, &t);
|
QMetaType::convert(v.metaType(), v.constData(), targetType, &t);
|
||||||
|
@ -169,6 +169,7 @@ private slots:
|
|||||||
void qvariant_cast_QObject_derived();
|
void qvariant_cast_QObject_derived();
|
||||||
void qvariant_cast_QObject_wrapper();
|
void qvariant_cast_QObject_wrapper();
|
||||||
void qvariant_cast_QSharedPointerQObject();
|
void qvariant_cast_QSharedPointerQObject();
|
||||||
|
void qvariant_cast_const();
|
||||||
|
|
||||||
void toLocale();
|
void toLocale();
|
||||||
|
|
||||||
@ -2579,6 +2580,17 @@ void tst_QVariant::qvariant_cast_QSharedPointerQObject()
|
|||||||
qRegisterMetaType<QSharedPointer<QObject> >();
|
qRegisterMetaType<QSharedPointer<QObject> >();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void tst_QVariant::qvariant_cast_const()
|
||||||
|
{
|
||||||
|
int i = 42;
|
||||||
|
QVariant v = QVariant::fromValue(&i);
|
||||||
|
QVariant vConst = QVariant::fromValue(const_cast<const int*>(&i));
|
||||||
|
QCOMPARE(v.value<int *>(), &i);
|
||||||
|
QCOMPARE(v.value<const int *>(), &i);
|
||||||
|
QCOMPARE(vConst.value<int *>(), nullptr);
|
||||||
|
QCOMPARE(vConst.value<const int *>(), &i);
|
||||||
|
}
|
||||||
|
|
||||||
void tst_QVariant::convertToQUint8() const
|
void tst_QVariant::convertToQUint8() const
|
||||||
{
|
{
|
||||||
/* qint8. */
|
/* qint8. */
|
||||||
|
Loading…
x
Reference in New Issue
Block a user