11

Does Qt have its own boost::optional alternative, or should I just use boost::optional?

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151

5 Answers5

8

Qt has a 'variant' type, but not an 'optional' type. I think that boost::optional (or, in newer C++ versions, std::optional) is a reasonable choice.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • As an addendum, programmers prefer Qt types over the stdlib alternatives (for example, QVariant vs std::variant, QVector vs std::vector, etc) due to the Qt functions doing processing with them natively, obviating conversions. However due to the nonexistence of a Qt optional type, it's perfectly reasonable to use std::optional. –  Aug 05 '21 at 03:40
6

Seems like QVariant already can do what boost::optional was intended to do. You have:

bool QVariant::isNull() const
bool QVariant::isValid() const
Type QVariant::type() 
static QVariant QVariant::fromValue(const T & value)
T QVariant::value()

So you can wrap any type, check if the variant is null or valid or even get the type to use with an if or switch statement.

dtech
  • 47,916
  • 17
  • 112
  • 190
  • 7
    Sure but QVariant is an overkill. It has more overhead and hides type of its contents. – Sergey Galin Apr 11 '18 at 14:07
  • 1
    If one already uses Qt it is a viable option, I doubt it will end up used in places where its memory or performance overheads will be exacerbated. – dtech Apr 11 '18 at 14:11
  • 2
    QVariant isn't a good fit for the use case of optionals. From the docos for QVariant: Null variants is not a single state and two null variants may easily return false on the == operator if they do not contain similar null values. – Andrew Lipscomb Mar 03 '19 at 02:51
3

In C++17 there was introduced std::optional: https://en.cppreference.com/w/cpp/utility/optional

I think it's more usefull in Qt project, than boost one. There is still no any QOptional class in Qt.

Nikxp
  • 355
  • 3
  • 13
2

There is qt-maybe template implemented on top of Qt's QVariant container, but it's not in "standard" qt lib.

Konrad 'Zegis'
  • 15,101
  • 1
  • 16
  • 18
1

No there is no alternative for boost::optional at present. You can also refer this thread: boost::optional alternative in C++ Standard Library

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331