Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

New in Qt 6.1: std::hash Support for QHash

class MyClass {
// ...
};

namespace std {
template <> struct hash<MyClass>
{
    size_t operator()(const MyClass &c, size_t seed = std::hash<int>{}(0)) const noexcept {
       // ~~~
    }
}:
} // std

QHash<MyClass, Data> hash;               // OK
std::unordered_map<MyClass, Data> hash2; // OK
size_t qHash(const MyType &t, size_t seed = 0) noexcept
{
  return qHash(t.key, seed); // <-- qHash used as public API
}
// Assume we have a magic IsQtClass<T> trait
// that tells us if T is a class that belongs to Qt

template <typename T>
concept QtHashableClass = requires(const T &t) {
    IsQtClass<T>;
    { qHash(t, std::declval<size_t>()) } -> std::same_as<size_t>;
};

namespace std
{
template <typename T>
requires QtHashableClass<T>
struct hash<T>
{
    size_t operator()(const T &t, size_t seed = std::hash<int>{}(0)) const noexcept
    {
        return qHash(t, seed);
    }
};
} // std

std::unordered_set< /* Any Qt datatype here */ > set; // just works

About KDAB


GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Learn Modern C++

Learn more