-1

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.

N. Kudryavtsev
  • 3,556
  • 1
  • 26
  • 30

2 Answers2

1

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.

dtech
  • 47,916
  • 17
  • 112
  • 190
0

@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).

N. Kudryavtsev
  • 3,556
  • 1
  • 26
  • 30
  • 1
    "One cannot use a non-const reference as a key" - actually that's perfectly possible. The problem is not that the key isn't a constant, but that it depends on a non constant, if `SomeQStringMember` is to change, that would break the hash table. – dtech May 14 '17 at 18:59