# Direct comparing of two QVariant variables

• There cannot be a clean solution for an in principle unsolvable problem. QVariant can hold types which are plain not comparable. For int an QStringList one can imagine something fancy, but comparing a QVariantMap against a QImage is ... weird.

So, you will have to constraint your comparison - this is were your home brown solution enters the game.

For using a template based solution, something like this comes into mind:

@
template<typename T>
bool qVariantLessThan(const QVariant &l, const QVariant &r)
{
QVariant l2 = qvariant_cast<T>(l);
QVariant r2 = qvariant_cast<T>(r);

``````if(l.type() != l2.type() || l != l2) {
qFatal("QVariant lessThan: l is not of correct type!");
return false;
}

if(r.type() != r2.type() || r != r2) {
qFatal("QVariant lessThan: r is not of correct type!");
return false;
}

return l.value<T>() < r.value<T>();
``````

}

QVariant s1("x1");
QVariant s2("x2");
qDebug() << qVariantLessThan<QString>(s1, s2);
// true

QVariant i1(1);
QVariant i2(-1);
qDebug() << qVariantLessThan<int>(i1, i2);
// false

QVariant d1(1.25);
QVariant d2(1.24);
qDebug() << qVariantLessThan<double>(d1, d2);
// false

QVariant f1(1.25f);
QVariant f2(1.26f);
qDebug() << qVariantLessThan<float>(f1, f2);
// true

qDebug() << qVariantLessThan<float>(d1, f2);
// error

qDebug() << qVariantLessThan<float>(f1, f2);
// error
@

I don't know whether it's possible to overload operator<() at all. Even if it was possible a syntax like

@
bool lessThan = x1 < <int> x2;
@

would be weird at best.

• [quote author="Volker" date="1326642057"]There cannot be a clean solution for an in principle unsolvable problem. QVariant can hold types which are plain not comparable. For int an QStringList one can imagine something fancy, but comparing a QVariantMap against a QImage is ... weird[/quote]

If QVariant knows (and it does) about the type of the value it stores, why can't it return this value with QVariant::value() without type specification just as it returns with value<int>(), value<float>(), etc ad nauseum?

[quote author="Volker" date="1326642057"]For using a template based solution, something like this comes into mind[/quote]

This is not a real solution. As said before, it's better to make type casting directly in the if statement for comparison. In both cases you have to know the right type to which to convert at compile-time or to cover all possible (allowed) types. This is a real nuisance and in tight loops just a waste of cycles

• [quote author="deisik" date="1326646561"]If QVariant knows (and it does) about the type of the value it stores, why can't it return this value with QVariant::value() without type specification just as it returns with value<int>(), value<float>(), etc ad nauseum?[/quote]
It can't do that, because C++ won't let you. You cannot overload a method by only changing its return type. The only way to do it, is the way it has been done: as a templated method. How on earth is the compiler supposed to know what the return type of QVariant::value() is?

[quote author="deisik" date="1326646561"]This is not a real solution. As said before, it's better to make type casting directly in the if statement for comparison. In both cases you have to know the right type to which to convert at compile-time or to cover all possible (allowed) types. This is a real nuisance and in tight loops just a waste of cycles[/quote]

I am wondering if QVariant really is the type for you. If you know you are storing a certain type, why not use that type directly then? QVariant has its uses, but in the end, it still is little more than a glorified void* after all.

• [quote author="Andre" date="1326656285"]It can't do that, because C++ won't let you. You cannot overload a method by only changing its return type. The only way to do it, is the way it has been done: as a templated method. How on earth is the compiler supposed to know what the return type of QVariant::value() is?[/quote]

Why should the compiler know anything if the return type can just be a void* pointer of that very QVariant::value() without explicit type cast (or call it valueVoid() for that matter)? I don't mean overloading and again, I see no problem here - qt knows the right type, so does the programmer

[quote author="Andre" date="1326656285"]I am wondering if QVariant really is the type for you. If you know you are storing a certain type, why not use that type directly then? QVariant has its uses, but in the end, it still is little more than a glorified void* after all. [/quote]

I have the same thoughts but I don't like the idea of doing some very low level (read nasty) things in qt/c++. Look, in c/c++ you can easily reinterpret some portion of memory as you like on the fly and you cheerfully hope that the exact way you do this can just as easy be determined by some other bytes in memory you point to, but nope, you can't do this

• [quote author="deisik" date="1326660493"]
Why should the compiler know anything if the return type can just be a void* pointer of that very QVariant::value() (or call it valueVoid() for thet matter) without explicit type cast? Again, I see no problem here - qt knows the right type, so does the programmer
[/quote]

The signature of method value is

@
template <typename T>
T QVariant::value();
@

T is a type and must be know at compile time. The pure reason for the existence of QVariant is that its type is not know at compile time, but only during runtime. So we have an unresolvable problem here. This is a limitation of C++, as Andre already stated, so Qt cannot be of any help here.

• [quote author="Volker" date="1326661096"]T is a type and must be know at compile time[/quote]

I agree, but this is not the matter in question. Make another method, call it whatever, let it return void* pointer, and compiler is out of question

• [quote author="deisik" date="1326660493"]Why should the compiler know anything if the return type can just be a void* pointer of that very QVariant::value() without explicit type cast (or call it valueVoid() for that matter)? I don't mean overloading and again, I see no problem here - qt knows the right type, so does the programmer[/quote]
But that would not help you solve your problem, I think? I mean, comparing two void pointers would compare their addresses, not their contents. So, that would force to to start casting again, and then you're back to where you started.

• And what do you want to do with the void pointer? That is as opaque as the QVariant itself...

• [quote author="Andre" date="1326661453"]But that would not help you solve your problem, I think? I mean, comparing two void pointers would compare their addresses, not their contents. So, that would force to to start casting again, and then you're back to where you started. [/quote]

Yes, there is a problem here but it deserves and requires thorough thinking over. At least we are no longer bound to QVariant without losing its advantages

• [quote author="Volker" date="1326661563"]And what do you want to do with the void pointer? That is as opaque as the QVariant itself...[/quote]

I can ask you another question, how QVariant itself stores its value data type?

• [quote author="deisik" date="1326661825"]
Yes, there is a problem here but it deserves and requires thorough thinking over. At least we are no longer bound to QVariant without losing its advantages[/quote]

When passing a void pointer to another method (operators are methods too) you even loos the information that it actually is a QVariant. We're all looking forward to see your implementation outline of a lessThan implementation taking to void pointers, though. I'm pretty sure neither Andre, nor me or anyone else we both know a decent solution, be we're all eager to learn something new (as everyone doing software development should do).

• A void* caries less information than QVariant. I don't see how that would bring you any closer to a solution.

• [quote author="deisik" date="1326662003"][quote author="Volker" date="1326661563"]And what do you want to do with the void pointer? That is as opaque as the QVariant itself...[/quote]

I can ask you another question, how QVariant itself stores its value data type?

[/quote]

http://qt.gitorious.org/qt/qt/blobs/4.8/src/corelib/kernel/qvariant.h#line358

• [quote author="Andre" date="1326662334"]A void* caries less information than QVariant. I don't see how that would bring you any closer to a solution. [/quote]

This information about data type is known beside QVariant (read saved somewhere else) - this is the whole point of my question. How to use it for comparison and whether it is possible in c++ at all is another question

• [quote author="Volker" date="1326662484"]http://qt.gitorious.org/qt/qt/blobs/4.8/src/corelib/kernel/qvariant.h#line358[/quote]

I expected to see something like that

• [quote author="deisik" date="1326662787"][quote author="Andre" date="1326662334"]A void* caries less information than QVariant. I don't see how that would bring you any closer to a solution. [/quote]

This information about data type is known beside QVariant (read saved somewhere else) - this is the whole point of my question. How to use it for comparison and whether it is possible in c++ at all is another question[/quote]

You put void pointers into the game, so it's your turn to show how it eases solving the problem, not ours. Our opinion is known (void pointers make matters worse). The other constraints, set by C++, have already been pointed out.

[quote author="deisik" date="1326662903"][quote author="Volker" date="1326662484"]http://qt.gitorious.org/qt/qt/blobs/4.8/src/corelib/kernel/qvariant.h#line358[/quote]

I expected to see something like that

[/quote]

Reading source code is the best way of understanding things. What else would you have hoped to see instead of your expectations?

• [quote author="Volker" date="1326663446"]
You put void pointers into the game, so it's your turn to show how it eases solving the problem, not ours. Our opinion is known (void pointers make matters worse). The other constraints, set by C++, have already been pointed out.[/quote]

Ok, I will make a try

[quote author="Volker" date="1326663446"]Reading source code is the best way of understanding things. What else would you have hoped to see instead of your expectations?[/quote]

To hope for something out of nothing is the most popular form of hope. Black magic indeed

• [quote author="Volker" date="1326663446"]
You put void pointers into the game, so it's your turn to show how it eases solving the problem, not ours[/quote]

My try as promised. I am interested in comparing ints, floats and strings and as I said earlier data type for each value is known. This means that we know beforehand the length the byte array representing this or that value takes in memory. So the algorithm for comparing two values is to regard them as, say, 64 bits integers, filling the higher missing bits of the shorter values (copy of) with zeroes (to clean up garbage)

This technique should work even for real numbers. In fact, interpreting the bit-pattern of a floating-point number as integer is one of the methods for comparing floats and doubles (as a side note, you cannot correctly compare two floats by comparing them "out of the box" as you suggested in the code snippet, but I think you know this yourself)

There still remains a minor problem with negative numbers but as it happens I am not much interested in them (in my case there are none), furthermore I guess this can be fixed somehow

Now you give me a void pointer to a QVariant value and I show you the code

• [quote]I am interested in comparing ints, floats and strings and as I said earlier data type for each value is known.[/quote]

Do you mean that the variants you want to compare are only of these three types? An arbitrary string or a string representing a number as well? (In the former case, how do you compare it f.i. against a number?)

• [quote author="peppe" date="1326672292"]Do you mean that the variants you want to compare are only of these three types? An arbitrary string or a string representing a number as well? (In the former case, how do you compare it f.i. against a number?)[/quote]

There can be no comparison between defferent types (imagine a table where you compare only between values of the same column). And yes, columns of this imaginary table are almost all kinds of unsigned base types but they are all interpreted as quint64 integer for saving in a binary file (well, this is a waste of space but it saves time when retrieving them and when we come to file sizes over a few GBs it makes no difference - you just save the value in place of otherwise a 64 bit pointer)

[quote author="peppe" date="1326672292"]An arbitrary string or a string representing a number as well? (In the former case, how do you compare it f.i. against a number?)[/quote]

Yes, arbitrary text strings. In case there is a "number" inside it is valid to consider it as text. So "75" would actually be 55 53 as a byte array

There are also QDateTimes but they are converted to uints with QDateTime::toTime_t(). In fact, all these types pass in QVariant as raw bytes (by QByteArray) and converted to real int, floats, strings and dates only for representation through QAbstractItemModel and building indexes (where comparison comes into play). It is a matter of interpretation

• And it seems now that I can really make comparisons without QVariant entirely through byte arrays

• I am still wondering how this byte comparison is going to help you achieve the goal you stated earlier:

[quote author="deisik" date="1326624029"]How can this help me find out which value is greater and which is less?[/quote]

How, you think, is a byte-level comparision going to help you compare two QStrings stored in that QVariant union? I mean: you do realize that the actual character array is not stored within the QVariant, right?

• [quote author="Andre" date="1326703007"]How, you think, is a byte-level comparision going to help you compare two QStrings stored in that QVariant union? I mean: you do realize that the actual character array is not stored within the QVariant, right?
[/quote]

Right, it is stored somewhere in memory, so rises the question of a void* pointer to this character array. You seem to be missing the whole point of what I say

• Then, I guess we just don't understand each other. I wish you all the luck with your attempts to efficiently compare QVariants, but I don't think I can contribute to this discussion anymore. Please let us know if you find an efficient solution, I would be interested to see it.

• [quote author="Andre" date="1326707128"]Then, I guess we just don't understand each other. I wish you all the luck with your attempts to efficiently compare QVariants, but I don't think I can contribute to this discussion anymore. Please let us know if you find an efficient solution, I would be interested to see it. [/quote]

I have already shown a clean solution which I am going to pick up myself. You probably confuse a pointer to a QVariant object as such with a pointer to data which this object wraps around and to which it should provide this pointer (as a void*) - I talk about the latter

• [quote author="deisik" date="1326707907"]I have already shown a clean solution which I am going to pick up myself. You probably confuse a pointer to a QVariant object as such with a pointer to data which this object wraps around and should provide as a void* - I talk about the latter[/quote]

If I understood correctly, you want to use the pointer to the memory to do the comparison, right?
How do you know, how to interpret the raw memory segment? The memory representation of a double is different from an int is different from .... So you again need the information to do correct comparison. Where is the benefit?

• [quote author="Gerolf" date="1326708249"]If I understood correctly, you want to use the pointer to the memory to do the comparison, right?[/quote]

Yes, you got it right

[quote author="Gerolf" date="1326708249"]How do you know, how to interpret the raw memory segment?[/quote]

There is no need to interpret this segment in the sense you mean by "interpreting". You just need to know its length, that's all

[quote author="Gerolf" date="1326708249"]The memory representation of a double is different from an int is different from .... So you again need the information to do correct comparison. Where is the benefit?[/quote]

I have already answered this question above - just read about how doubles and floats are accurately compared to each other

• a double is represented by 8 bytes, mantisse and exponent. They have influence on how to read each other. If you do a byte compare, that does not work.

• [quote author="Gerolf" date="1326709312"]a double is represented by 8 bytes, mantisse and exponent[/quote]

Yes, 64 bits

[quote author="Gerolf" date="1326709312"]They have influence on how to read each other. If you do a byte compare, that does not work.[/quote]

It will. Just use 64 bits integers. Check yourself

• By the way, if all numbers are allowed (positive as well as negative) you can safely check the sign of the difference between the two values, so the method seems to be universal

• If you do things like this, please leave a note for the next developer to start debugging right here if the application starts to crash somewhen.
@
void lessThan(void* left, void* right)
{
return (quint64)left < (quint64)right;
}
@
Another rule one might stick to: even if it is possible, it doesn't mean that it should be done that way.

• [quote author="Lukas Geyer" date="1326717017"]If you do things like this, please leave a note for the next developer to start debugging right here if the application starts to crash somewhen.
@
void lessThan(void* left, void* right)
{
return (quint64)left < (quint64)right;
}
@
Another rule one might stick to: even if it is possible, it doesn't mean that it should be done that way.[/quote]

If the code is like this, it might crash if the value is not 64 bit long and not enough memory to read is there. Additionally, it might bring problems with little / big endianess, right?

• As long as you stick to the OPs self-imposed limitations [limited set of datatypes, fixed size of 64 bit for every datatype, fixed floating point format, non-portable (including endianess)] this code actually does work. However, this usually does not justify the use of such code in production, as it will break on first occasion.

• [quote author="Lukas Geyer" date="1326717017"]If you do things like this, please leave a note for the next developer to start debugging right here if the application starts to crash somewhen.
@
void lessThan(void* left, void* right)
{
return (quint64)left < (quint64)right;
}
@
Another rule one might stick to: even if it is possible, it doesn't mean that it should be done that way.[/quote]

Just add the lengths of the byte arrays to the function declaration and make proper use of them within and almost all of the pitfalls you talk about will go away

You cannot take measures of safety against everything. If you try, you will inevitably fall into an endless loop

• But if you add the length, you add information that is type specific. This means some if at call, which you wanted to remove.

• [quote author="deisik" date="1326724760"]
You cannot take measures of safety against everything. If you try, you will inevitably fall into an endless loop[/quote]

You can by avoiding a design that is broken from the very beginning.

I'm not now.

• [quote author="Gerolf" date="1326726540"]But if you add the length, you add information that is type specific. This means some if at call, which you wanted to remove.[/quote]

For sanity check. I personally would not need it since I know that other constraints make it redundant. Period

This is what the word "integrity" stands for

• [quote author="Volker" date="1326726676"]You can by avoiding a design that is broken from the very beginning[/quote]

Sorry, this won't help you. If it would, there would be no bugs in the software which is written with the aim "of avoiding a design that is broken from the very beginning"

• [quote author="deisik" date="1326724760"]
Just add the lengths of the byte arrays to the function declaration and make proper use of them within and almost all of the pitfalls you talk about will go away

You cannot take measures of safety against everything. If you try, you will inevitably fall into an endless loop[/quote]

You lose the limitation of fixed sizes, but you are still limited to some datatypes, you are still limited to a fixed floating point format and your code is non-portable by any means, because you rely on archtictural and implementational details.

What happens if the two sizes do differ? Do you start creating buffers within <code>lessThan()</code>? What if the size exceeds <code>sizeof(quint64)</code>, for example QINT64_MAX in string representation? Do you add your own comparison algorithm? How can you assure that <code>lessThan()</code> is only invoked with supported datatypes, as every datatype fits in void*? What if you compiler or FPU implementation does not support or use IEEE 754?

Of course you can't take measures of safety against everything, but you still have to assure that your code is as least error-prone as possible. One way to achieve this is to make use of C++s type safety, which is completely nullified by void pointers and C-style casts. Your code doesn't get flexible, it just gets error-prone.

It was a nice brain-twister, for all of us; and there is a use case where it actually works - but do yourself a favor and just use "correct" code. Everything else will lead to serious problems sooner or later.
@
bool lessThan(int left, int right)
{
return left < right;
}

bool lessThan(double left, double right)
{
return left < right;
}

bool lessThan(const char* left, const char* right)
{
// if you need further saftey or error handling use
// stringstream, boost::lexical_cast or just QString

``````return atoi(left) < atoi(right);
``````

}

// An implementation for QVariant is found in other posts of this thread
@
This solution is just a few more lines (or, if you handle most of the limitations in your implementation, a lot less lines), absolutely type-safe, easily extensible and understandable and as least error-prone as possible.

• [quote author="Lukas Geyer" date="1326727414"]You lose the limitation of fixed sizes, but you are still limited to some datatypes, you are still limited to a fixed floating point format and your code is non-portable by any means, because you rely on archtictural and implementational details. What happens if the two sizes do differ? Do you start creating buffers within <code>lessThan()</code>? What if the size exceeds <code>sizeof(quint64)</code>, for example QINT64_MAX in string representation? Do you add your own comparison algorithm? How can you assure that <code>lessThan</code> is only invoked with supported datatypes, as every datatype fits in void? What if you compiler or FPU implementation does not support IEEE 754?[/quote]

It is for sanity sake only. As I said before there is no need for it because other limitations and conditions would exclude it to a certain degree. And at that you cannot write code that fits everyone or is suitable for every purpose or supposed to run everywhere, you have to make trade-offs - it is just a matter of understanding what is possible and what is not in the given conditions (please, note). Yes, conditions may change but they may also change in such a way that your software will come to be just a piece of garbage despite it being of a "correct design"

[quote author="Lukas Geyer" date="1326727414"]It was a nice brain-twister, for all of us; and there is a use case where it actually works - but do yourself a favor and just use "correct" code. Everything else will lead to serious problems sooner or later[/quote]

Everything potentially can lead to any kind of problems - it is just a matter of time