Reputation: 3294
I have a QHash<const QString id, MyClass>
, whereas MyClass is just a collection of some QString quint8 values with getters and setters. MyClass also has a QDataStream &operator<<(QDataStream &ds, const MyClass &obj)
overwritten, there.
To serialize I use:
typedef QHash<const QString, MyClass> MyClassHash;
//..
QDataStream &operator<<(QDataStream &ds, const MyClassHash &obj) {
QHashIterator<const QString, MyClass> i(obj);
while(i.hasNext())
{
i.next();
QString cKey = i.key();
ds << cKey << i.value();
}
return ds;
}
Now, I am confused with the other:
QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
obj.clear();
// ?
return ds;
}
I would I know the legth of that serialized QHash ?
Upvotes: 0
Views: 524
Reputation: 22826
You do not provide operator<<
and operator>>
for QHash; their implementation is already provided for you by Qt.
As long as both your key type and your value type are serializable using QDataStream, then you're good to go:
class MyClass
{
int i;
friend QDataStream &operator<<(QDataStream &ds, const MyClass &c);
friend QDataStream &operator>>(QDataStream &ds, MyClass &c);
};
QDataStream &operator<<(QDataStream &ds, const MyClass &c)
{
ds << c.i;
return ds;
}
QDataStream &operator>>(QDataStream &ds, MyClass &c)
{
ds >> c.i;
return ds;
}
int main()
{
QHash<QString, MyClass> hash;
QDataStream ds;
// doesn't do anything useful, but it compiles, showing you
// that you don't need any custom streaming operators
// for QHash
ds << hash;
ds >> hash;
}
Upvotes: 1
Reputation: 756
Whatabout the QDataStream::status :
QDataStream &operator>>(QDataStream &ds, MyClassHash &obj) {
obj.clear(); // clear possible items
Myclass cMyCls;
while (!ds.status()) { // while not finished or corrupted
ds >> cKey >> cMyCls;
if (!cKey.isEmpty()) { // prohibits the last empty one
obj.insert(cKey, cMyCls);
}
}
return ds;
}
Upvotes: 1
Reputation: 9404
Obviously, there are two ways to do things:
operator<<
before save items of QHash you should save QHash::sizeoperator<<
save some invalid QString, for example empty QString, and in operator>>
, stop reading when we meet such value.Upvotes: 0