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

Support std::optional in QDataStream

    XMLWordPrintable

Details

    • Suggestion
    • Resolution: Unresolved
    • P3: Somewhat important
    • None
    • 5.15
    • Core: I/O
    • None
    • 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

        For Gerrit Dashboard: QTBUG-92368
        # Subject Branch Project Status CR V

        Activity

          People

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

            Dates

              Created:
              Updated:

              Gerrit Reviews

                There is 1 open Gerrit change