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 |
詳細な説明
主な使用例の1つは、ポインタを比較する際の未定義の振る舞い(UB) を防ぐことです。
次のような単純なクラスを考えてみましょう:
template <typename T> struct PointerWrapperBad { int val; T *ptr; };
PointerWrapperBad
型の2つのインスタンスをレキシカルに比較すると、operator<()
またはoperator<=>()
がptr
のメンバ上で呼び出されるため、UBが発生します。
これを修正するには、新しいラッパー型を使います:
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
を使うこともできる。
© 2025 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.