Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-92368

Support std::optional in QDataStream

    XMLWordPrintable

    Details

    • Type: Suggestion
    • Status: Open
    • Priority: P3: Somewhat important
    • Resolution: Unresolved
    • Affects Version/s: 5.15
    • Fix Version/s: None
    • Component/s: Core: I/O
    • Labels:
      None
    • Platform/s:
      All

      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

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

            Assignee:
            thiago Thiago Macieira
            Reporter:
            ssproessig Sören Sprößig
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated:

                Gerrit Reviews

                There are no open Gerrit changes