Writing custom qhash() function for my class

1.4k Views Asked by At

I would like to use a QHash<MyOwnClass&, MyOwnEnum> (as a member of MyOwnClass if it does matter). Docs say that one should define a global qhash(MyOwnClass&) function. OK, for example:

globals.h:

#pragma once
#include "myOwnClass.h"
#include <QHashFunctions>

class MyOwnClass;

inline uint qHash(MyOwnClass& clz);

globals.cpp:

#include "globals.h"

inline uint qHash(MyOwnClass& clz) {
    return qHash(clz.getSomeQStringMember());
}

Where should I include my globals.h, so that the compiler will be able to see and use it?

I'm using MSVS2015 and Qt 5.8. I believe this question is silly and has very simple solution, as long as the answer would help many others like me.

2

There are 2 best solutions below

0
On

If you have a custom type that you will be using in a hash, it will be best to simply declare the function in the same header which declares MyOwnClass. It goes hand in hand with that class after all, you don't need a globals.h in order to have a global function, it just needs to be in the global scope and not be static.

You will also have to #include <QHash> where you define your hash function (the implementation), so it can have access to the existing hash implementations.

Edit: I see that you include #include <QHashFunctions> which should give you the function to hash a QString. So you probably need to clean and rebuild your project.

1
On

@dtech 's answer is worth to be read but it did not solve my issue completely.

One cannot use a non-const reference as a key in QHash, so I should declare it as QHash<const MyOwnClass&, MyOwnEnum> and define function qHash(const MyOwnClass& clz) (as long as an equality operator, of course).