Qt 中的 C++20 比较(即使使用 C++17)

  • Overview of C++20 comparison enhancements in Qt 6.7 and how to implement them in custom classes.
  • Qt's C++17 back-ported comparison types and helper methods.
  • Implementation examples of three-way comparisons using Qt::compareThreeWay() and qCompareThreeWay().

Main points and key information:

  • C++20 introduced the three-way comparison operator <=> (spaceship operator) with three possible result types: std::strong_ordering, std::weak_ordering, or std::partial_ordering.
  • Qt 6.7 supports C++17 and has made C++20 comparison-related functionalities available, including its own comparison types and helper methods in <QtCore/QtCompare>.
  • In Qt 6.7, some Qt classes like QDate, QTime, QDateTime, QTimeZone, and qfloat16 were updated to use modernized comparisons with helper functions.
  • Examples are provided for implementing three-way comparisons using Qt::compareThreeWay() and qCompareThreeWay(), showing how to handle different types and member variables.

Important details:

  • Qt::compareThreeWay() provides a three-way comparison for built-in C++ types and mimics the spaceship operator's behavior in C++17.
  • qCompareThreeWay() is a template function for generic code and requires compareThreeWay() to be implemented for the types being compared.
  • The return type of compareThreeWay() must be one of Qt's comparison types.
  • Take advantage of named comparison functions like is_eq() and is_lt() for operator==() and operator<().
  • In the examples, different types of classes and their member variables are used to demonstrate the implementation of three-way comparisons.
阅读 20
0 条评论