En esta página

Qt::totally_ordered_wrapper Class

template <typename P> class Qt::totally_ordered_wrapper

Qt::totally_ordered_wrapper es un tipo de envoltura que proporciona un orden total estricto para los tipos envueltos. Más...

Cabecera: #include <QtCompare>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Desde: Qt 6.8

Descripción detallada

Uno de sus principales usos es prevenir el Comportamiento Indefinido (UB) cuando se comparan punteros.

Considere la siguiente clase simple:

template <typename T>
struct PointerWrapperBad {
    int val;
    T *ptr;
};

La comparación lexicográfica de las dos instancias del tipo PointerWrapperBad resultaría en UB, porque llamará a operator<() o operator<=>() en los miembros ptr.

Para solucionarlo, utilice el nuevo tipo envoltorio:

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;
};

Los operadores operator<() y (si está disponible) operator<=>() para el tipo Qt::totally_ordered_wrapper utilizan los objetos de función std ::less y std::compare_three_way respectivamente, proporcionando un orden total estricto sobre los punteros al realizar la comparación.

Como resultado, los operadores relacionales para el miembro PointerWrapperGood::ptr estarán bien definidos, e incluso podemos =default los operadores relacionales para la clase PointerWrapperGood, como se muestra arriba.

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