Qt::totally_ordered_wrapper is a wrapper type that provides strict total order for the wrapped types. More...
| Header: | #include <QtCompare>
|
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Core)target_link_libraries(mytarget PRIVATE Qt6::Core)
|
| qmake: | QT += core
|
| Since: | Qt 6.8 |
One of its primary usecases is to prevent Undefined Behavior (UB) when comparing pointers.
Consider the following simple class:
template <typename T>
struct PointerWrapperBad {
int val;
T *ptr;
};Lexicographical comparison of the two instances of the PointerWrapperBad type would result in UB, because it will call operator<() or operator<=>() on the ptr members.
To fix it, use the new wrapper type:
template <typename T>
struct PointerWrapperGood {
int val;
Qt::totally_ordered_wrapper<T *> ptr;
friend bool
operator==(PointerWrapperGood lhs, PointerWrapperGood rhs) noexcept = default;
friend auto
operator<=>(PointerWrapperGood lhs, PointerWrapperGood rhs) noexecpt = default;
};The operator<() and (if available) operator<=>() operators for the Qt::totally_ordered_wrapper type use the std::less and std::compare_three_way function objects respectively, providing strict total order over pointers when doing the comparison.
As a result, the relational operators for PointerWrapperGood::ptr member will be well-defined, and we can even =default the relational operators for the PointerWrapperGood class, like it's shown above.
© The Qt Company Ltd
Licensed under the GNU Free Documentation License, Version 1.3.
https://doc.qt.io/qt-6.9/qt-totally-ordered-wrapper.html