Qt::totally_ordered_wrapper Class
template <typename P> class Qt::totally_ordered_wrapperQt::totally_ordered_wrapper 是一种包装类型,为被包装的类型提供严格的总序。更多内容...
| 头文件: | #include <QtCompare> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Core) target_link_libraries(mytarget PRIVATE Qt6::Core) |
| qmake: | QT += core |
| 自: | Qt 6.8 |
公共函数
详细说明
Qt::totally_ordered_wrapper<P> 是一个模板类,其中P 指定要封装的类型。
其主要用例之一是防止在比较指针时出现未定义行为(UB)。
考虑以下简单类:
template <typename T>
struct PointerWrapperBad {
int val;
T *ptr;
};对PointerWrapperBad 类型的两个实例进行字典序比较会导致未定义行为(UB),因为这会调用ptr 成员的operator<() 或operator<=>() 方法。
要解决此问题,请使用新的包装类型:
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;
};针对Qt::totally_ordered_wrapper 类型的operator<() 和(若可用)operator<=>() 运算符,分别使用std::less和std::compare_three_way函数对象,在进行比较时为指针提供严格的总序。
因此,PointerWrapperGood::ptr 成员的比较运算符将被明确定义,我们甚至可以像上文所示那样,为PointerWrapperGood 类=default 其比较运算符。
成员函数文档
[noexcept default] totally_ordered_wrapper::totally_ordered_wrapper()
默认——构造一个totally_ordered_wrapper 的实例。
© 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.