[Development] Converting types in Qt

Poenitz Andre Andre.Poenitz at digia.com
Wed Jul 16 11:54:07 CEST 2014


Olivier Goffart:
> Poenitz Andre wrote:
> > I wholeheartedly disagree. Most of my QVariant uses are there because
> > the Qt API requires me to use it, and I sometimes use it voluntarily for
> > type-agnostic storage or transport of "things". But in those cases I never
> > want to extract anything else from the variant than exactly the "thing"
> > I put into it.
> 
> So if I understand you and Eike correctly, what you want is some kind of
> 
> template<typename T> T qvariant_cast_safe(const QVariant &v) {
>         Q_ASSERT(v.userType() == qMetaTypeId<T>())
>     return *reinterpret_cast<const T *>(v.constData());
> }

This would alleviate the "environment dependency" of the problem, 
i.e. presumably increase the probability that the issue is caught in 
local testing. (Of course, a real compile-time check i.e. something
that would also catch errors in code paths that are not executed during 
testing would be preferable, but that's not achievable in this setup)

> I _never_ (at least not intentionally) use QVariant as a kind of "magic
> converter bag" where I put something in and get something
> "conveniently" munged back.

> > When you play with qml or itemview, it's cool that there is a
> > QVariant::toString()  that puts some string out in order to show 
> > to the user what's in it.

That's a one-way route for a specific purpose, pretty much like
qPrintable(). There's nothing wrong with a .toDisplay() (or similar)
function, but that's don't think this is the kind of type conversion
that triggered this thread.

Andre'



More information about the Development mailing list