totally_ordered_wrapper Class

template <typename P> class Qt::totally_ordered_wrapper

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

Detailed Description

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.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.