Does Qt have its own boost::optional alternative, or should I just use boost::optional?
5 Answers
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.

- 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
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.

- 47,916
- 17
- 112
- 190
-
7Sure but QVariant is an overkill. It has more overhead and hides type of its contents. – Sergey Galin Apr 11 '18 at 14:07
-
1If 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
-
2QVariant 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
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.

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

- 15,101
- 1
- 16
- 18
No there is no alternative for boost::optional at present. You can also refer this thread: boost::optional alternative in C++ Standard Library

- 1
- 1

- 168,305
- 31
- 280
- 331