Details
-
Suggestion
-
Resolution: Unresolved
-
P3: Somewhat important
-
None
-
5.15
-
None
Description
We are using std::optional in our DTOs as
#include <QDataStream> #include <optional> struct MyStruct { qint32 idx; QString title; std::optional<QString> comment; };
We needed to store them with QDataStream. Unfortunately, QDataStream does not yet support std::optional directly. Hence we created
template<class T> static QDataStream& operator<<(QDataStream& ds, std::optional<T> const& opt) { auto const hasValue = opt.has_value(); ds << hasValue; if (hasValue) { ds << opt.value(); } return ds; } template<class T> static QDataStream& operator>>(QDataStream& ds, std::optional<T>& opt) { bool hasValue; ds >> hasValue; if (hasValue) { T aT; ds >> aT; opt = aT; } else { opt = std::nullopt; } return ds; }
This stores the actual data value with its own operator<< with a Boolean flag in-front of it:
- In case the optional value is not set, this only stores false.
- Otherwise it stores true and value itself.
Maybe this is worth adding to Qt itself?
Attachments
Gerrit Reviews
For Gerrit Dashboard: QTBUG-92368 | ||||||
---|---|---|---|---|---|---|
# | Subject | Branch | Project | Status | CR | V |
555975,3 | QDataStream: add overload for std::optional<T> | dev | qt/qtbase | Status: NEW | 0 | 0 |