<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 을 반환합니다.
이것은 std::exchange()에 대한 Qt의 구현입니다. C++20 이전에는 constexpr
, C++23 이전에는 아니오라는 점에서만 std::exchange()와 다릅니다.
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-loop는 루프가 실행되는 동안 qExchange()의 결과를 유지하여 임시 변수 선언을 저장하므로 완벽하게 안전합니다. 하지만 qExchange()는 생성되지 않은 객체를 반환하므로 Qt 컨테이너가 분리될 수 있다는 점에 유의하세요.
참고: 이 함수는 std::conjunction_v<std::is_nothrow_move_constructible<T>,
std::is_nothrow_assignable<T &, U>>
가 true
일 때를 제외하고는 작동하지 않습니다.
[constexpr noexcept, since 6.2]
template <typename Enum> std::underlying_type_t<Enum> qToUnderlying(Enum e)
열거자 e 를 해당 열거의 기본 유형에 표현된 동등한 값으로 변환합니다.
이 함수는 Qt 6.2에 도입되었습니다.
© 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.