From d681107f1fcbaabe7da27ac51563434b81b95d8e Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 28 Dec 2015 15:58:03 +0100 Subject: [PATCH] Add qHash(std::pair) We already include in , so we might as well provide a qHash() overload for std::pair. [ChangeLog][QtCore] Added qHash(std::pair), defined in . Change-Id: I0f61c513e82e05ce9d2e56bcf18f3be9e2da4da9 Reviewed-by: Olivier Goffart (Woboq GmbH) --- src/corelib/tools/qhash.cpp | 17 +++++++++++++++++ src/corelib/tools/qhashfunctions.h | 9 +++++++++ .../tools/qhashfunctions/tst_qhashfunctions.cpp | 16 ++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/src/corelib/tools/qhash.cpp b/src/corelib/tools/qhash.cpp index 75f1e6a1bc..7520158293 100644 --- a/src/corelib/tools/qhash.cpp +++ b/src/corelib/tools/qhash.cpp @@ -711,6 +711,23 @@ void QHashData::checkSanity() Types \c T1 and \c T2 must be supported by qHash(). */ +/*! + \fn uint qHash(const std::pair &key, uint seed = 0) + \since 5.7 + \relates QHash + + Returns the hash value for the \a key, using \a seed to seed the calculation. + + Types \c T1 and \c T2 must be supported by qHash(). + + \note The return type of this function is \e{not} the same as that of + \code + qHash(qMakePair(key.first, key.second), seed); + \endcode + The two functions use different hashing algorithms; due to binary compatibility + constraints, we cannot change the QPair algorithm to match the std::pair one before Qt 6. +*/ + /*! \fn uint qHashRange(InputIterator first, InputIterator last, uint seed = 0) \relates QHash \since 5.5 diff --git a/src/corelib/tools/qhashfunctions.h b/src/corelib/tools/qhashfunctions.h index e15fbb07ac..c0109f3bbb 100644 --- a/src/corelib/tools/qhashfunctions.h +++ b/src/corelib/tools/qhashfunctions.h @@ -147,6 +147,15 @@ template inline uint qHash(const QPair &key, return ((h1 << 16) | (h1 >> 16)) ^ h2 ^ seed; } +template inline uint qHash(const std::pair &key, uint seed = 0) + Q_DECL_NOEXCEPT_EXPR(noexcept(qHash(key.first, seed)) && noexcept(qHash(key.second, seed))) +{ + QtPrivate::QHashCombine hash; + seed = hash(seed, key.first); + seed = hash(seed, key.second); + return seed; +} + QT_END_NAMESPACE #if defined(Q_CC_MSVC) diff --git a/tests/auto/corelib/tools/qhashfunctions/tst_qhashfunctions.cpp b/tests/auto/corelib/tools/qhashfunctions/tst_qhashfunctions.cpp index bde9433a24..6cd8c3d29d 100644 --- a/tests/auto/corelib/tools/qhashfunctions/tst_qhashfunctions.cpp +++ b/tests/auto/corelib/tools/qhashfunctions/tst_qhashfunctions.cpp @@ -115,6 +115,22 @@ void tst_QHashFunctions::qhash() QVERIFY(qHash(pA) != qHash(pB)); } + + { + std::pair p12(1, 2); + std::pair p21(2, 1); + + using QT_PREPEND_NAMESPACE(qHash); + + QVERIFY(qHash(p12) == qHash(p12)); + QVERIFY(qHash(p21) == qHash(p21)); + QVERIFY(qHash(p12) != qHash(p21)); + + std::pair pA(0x12345678, 0x12345678); + std::pair pB(0x12345675, 0x12345675); + + QVERIFY(qHash(pA) != qHash(pB)); + } } void tst_QHashFunctions::fp_qhash_of_zero_is_zero()