[SOLVED] QDataStream operator >> read to an enum
-
That is actually what I am doing. I simplified a bit for the above example though. Here's what I'm doing for the overload:
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
in >> ((quint32)&e); //Anything wrong with this? It certainly feels dirty//This also works, but I would love to one-line it quint32 buffer; in >> buffer; e = exampleEnum(buffer); return in;
}
@ -
Why don't you only cast enum to int
@exampleEnum a = First;
qDebug() << (int)a; // Outputs 0
@Same goes with QDataStream.
And you work with integer here on.
You can also cast back from int to enums the same way.Or I'm missing the point here ;-) .
Regards,
Jake -
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
in >> ((quint32)&e); //Anything wrong with this? It certainly feels dirty
return in;
}
@
or
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
//This also works, but I would love to one-line it
quint32 buffer;
in >> buffer;
e = exampleEnum(buffer);return in;
}
@I personally would prefer the second version as long as it does not consume too much CPU because called often. Gut feelings tell me that the first might be dangerous.
Just guessing not tried. How about this:
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
quint32 &tmp = e;
in >> tmp;
return in;
}
@
Possibly the compiler doesn't complain. -
[quote author="Jake007" date="1330543911"]Why don't you only cast enum to int
@exampleEnum a = First;
qDebug() << (int)a; // Outputs 0
@Same goes with QDataStream.
And you work with integer here on.
You can also cast back from int to enums the same way.Or I'm I missing the point here ;-) .
Regards,
Jake[/quote]
As I noted, there is no problem writing to the QDataStream (likewise qDebug) because it automatically casts to int.The trouble is that it does not know what to do when reading. I understand why it can't do it without overloading the operator.
What I would really like to do is something like this:
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
in >> (quint32)e;
return in;
}
@
But for some reason, it won't convert to quint32.The situation is that I'm receiving datagrams and converting them to structures. I don't think that detail is particularly relevant though to my question.
-
[quote author="koahnig" date="1330544180"]@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
quint32 &tmp = e;
in >> tmp;
return in;
}
@
Possibly the compiler doesn't complain. [/quote]Well, this works. It also caused me to realize why I couldn't cast to quint32. Because it is a reference to exampleEnum, not just the value. facepalm
This works:
@
QDataStream& operator >>(QDataStream& in, exampleEnum& e)
{
in >> (quint32&)e;
return in;
}
@Thanks!