I want to use a std::string as the key of a QHash:
QHash<std::string, QString> m_hash;
m_hash.insert("ABC", "DEF");
I implemented the required qHash:
inline qHash(const std::string& key, uint seed = 0)
{
qHash(QByteArray::fromRawData(key.data(), key.length()), seed);
}
Everything compiles correctly using MSVC, but gcc generates the following error:
error: no matching function for call to
qHash(const std::__cxx11::basic_string<char>&)
How should I resolve this isse?
Qt 6.1 and newer
Using
std::stringas a key is supported out of the box, as Qt now usesstd::hashas a fallback forqHash.Pre Qt 6.1
Short answer
Defining the
qHashfunction inside thestdnamespace may resolve the compiler error, but adding a function to thestdnamespace is undefined behaviour. So, it is not allowed.A workaround is to wrap
std::stringinside a helper class[1]:Long Answer
As stated in this bug report, one has to define the
qHashfunction inside the namespace ofstd::string:So, the correct definition of the required
qHashwould be:It is also mentioned in the Qt docs:
However, adding a function to the
stdnamespace is undefined behaviour. So, one is stuck using a non-ideal workaround.Further reading
qHashoverloading: https://www.kdab.com/how-to-declare-a-qhash-overload/