C++20 概述

Qt 6 officially requires C++17, however we are constantly working on supporting new C++ language features to make Qt faster and safer, and provide a better experience for our users.

This page gives a brief overview of C++20 features available in Qt.

支持 std::chrono

Various classes related to date and time have support for std::chrono features from older versions of C++. With the arrival of C++20, std::chrono has added new calendar types ,譬如 year_month_day , plus date and time representations , such as the system_clock 及其 time_point types. When Qt is built with C++20, it can now make use of these additions.

QDate and QDateTime now support conversion to and from the various calendar, date and date-time types, along with addition of duration types . QTimeZone now supports construction from a time_zone .

QSpan - a Qt version of std::span

The std::span class template is an addition to the standard library that provides a uniform way to access a contiguous portion of any contiguous container.

使用 std::span in the public APIs of Qt could provide significant advantages. However, Qt 6 only requires C++17, meaning it cannot have C++20 types in the API and ABI.

Qt 6.7 introduced QSpan - a Qt version of std::span . The API of the class is compatible with the std version. QSpan and std::span can be implicitly converted into each other. However, there are some differences between the classes. See the corresponding section in the QSpan class documentation 了解更多细节。

Three-way comparison operator

C++20 introduced operator<=>() , also known as the three-way comparison operator , and three ordering types to represent the results of the comparison:

In Qt 6.8, many of the QtCore classes got support for operator<=>() . To use the new operator, the user project must be compiled in C++20 mode.

However, starting from Qt 6.7, C++17 users can use our own equivalents of the std ordering types.

As a C++20 language feature, backporting operator<=>() to C++17 is not possible, but you can use the Qt::compareThreeWay() function, which acts like a C++17 version of operator<=>() for built-in C++ types (such as integers, floating-point, and enumeration types).

Qt also defines helper functions compareThreeWay() for various classes in QtCore . These are all implemented as hidden friends . Users can implement their own compareThreeWay() functions for custom types.

Finally, Qt provides a qCompareThreeWay () function template, which serves as a generic three-way comparison implementation. It relies on Qt::compareThreeWay() and the above-mentioned free compareThreeWay() 函数在其实现中。

Additional important features

Qt has also adopted a few more features from C++20, such as: