How to use `std::string` as key of `QHash`?

折月煮酒 提交于 2020-02-23 06:48:06

问题


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?


回答1:


Short answer

Define the qHash function inside the std namespace.

Long Answer

As stated in this bug report, one has to define the qHash function inside the namespace of std::string:

This is documented in the C++ standard. It's called Argument-Dependent Lookup. It says that searching for an unqualified qHash(T) will find it in T's namespace.

So, the correct definition of the required qHash would be:

namespace std
{
  inline qHash(const std::string& key, uint seed = 0)
  {
    qHash(QByteArray::fromRawData(key.data(), key.length()), seed);
  }
}

It is also mentioned in the Qt docs:

A QHash's key type has additional requirements other than being an assignable data type: it must provide operator==(), and there must also be a qHash() function in the type's namespace that returns a hash value for an argument of the key's type.

Further reading

  • https://en.wikipedia.org/wiki/Argument-dependent_name_lookup
  • https://en.cppreference.com/w/cpp/language/adl


来源:https://stackoverflow.com/questions/59910341/how-to-use-stdstring-as-key-of-qhash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!