<QtTypeTraits> - Qt Type Traits
型特性および変換に関する機能。詳細...
| Header: | #include <QtTypeTraits> |
| Since: | Qt 6.5 |
関数
| T | qExchange(T &obj, U &&newValue) |
(since 6.2) std::underlying_type_t<Enum> | qToUnderlying(Enum e) |
マクロ
(since 6.8) | QT_NO_QASCONST |
(since 6.6) | QT_NO_QEXCHANGE |
関数のドキュメント
[constexpr noexcept(...)] template <typename T, typename U = T> T qExchange(T &obj, U &&newValue)
obj の値をnewValue に置き換え、obj の元の値を返します。
これは Qt による std::exchange() の実装です。std::exchange() との違いは、C++20 以前でも既にconstexpr であり、C++23 以前でも既に noexcept であるという点のみです。
C++20やC++23の機能が必要ない場合は、std::exchange()の使用を強く推奨します。QT_NO_QEXCHANGE マクロを定義することで、qExchange()を使用不可にすることができます。
以下に、qExchange() を使用して移動コンストラクタを実装する方法を示します。
MyClass(MyClass &&other)
: m_pointer{qExchange(other.m_pointer, nullptr)},
m_int{qExchange(other.m_int, 0)},
m_vector{std::move(other.m_vector)},
...クラス型のメンバについては、その移動コンストラクタが適切に動作するため、std::move() を使用できます。しかし、生ポインタや整数型などのスカラー型の場合、移動はコピーと同じ扱いとなり、特にポインタに関しては、期待した動作とは異なります。 したがって、このような型には std::move() を使用できませんが、std::exchange()/qExchange() を使用することで、次のデータメンバーの初期化に至るまでに、元のオブジェクトのメンバーが確実にリセットされるようにできます。これは、コンストラクタが例外を発生させて終了する場合に役立つかもしれません。
以下に、qExchange() を使用して、反復処理対象のコレクションを消費するループを記述する方法を示します。
for (auto &e : qExchange(collection, {})
doSomethingWith(e);これは、以下の、はるかに冗長なコードと同等です:
{
auto tmp = std::move(collection);
collection = {}; // or collection.clear()
for (auto &e : tmp)
doSomethingWith(e);
} // destroys 'tmp'forループが実行されている間、qExchange()の結果が保持されるため、一時変数の宣言が不要となり、これは完全に安全です。ただし、qExchange()は非constオブジェクトを返すため、Qtコンテナが切り離される可能性がある点に注意してください。
注: std::conjunction_v<std::is_nothrow_move_constructible<T>,
std::is_nothrow_assignable<T &, U>> がtrue の場合、この関数はnoexceptとなります 。
[constexpr noexcept, since 6.2] template <typename Enum> std::underlying_type_t<Enum> qToUnderlying(Enum e)
列挙子 `e ` を、その列挙型の基底型で表される等価な値に変換します。
この関数は Qt 6.2 で導入されました。
© 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.