0

I was trying to define a custom hash function so that I can use my class inside unordered_sets and unordered_maps but I am facing the above error and I dont know what this means.

I have managed to replicate the error with the following MCVE.

#include <unordered_set>

class A {
    int num;
public:
    A(int num) : num(num) {}
    int getNum() const { return num; }
    bool operator==(const A& other) const { return num == other.getNum(); }
};

namespace std {
    template<>
    struct hash<A> {
        size_t operator()(const A& key) {
            return key.getNum();
        }
    };
}


int main() {
    std::unordered_set<A> mySet;
    mySet.emplace(1);

    return 0;
}

I dont understand what this error is all about since I learned about defining custom hash function very recently and this is my first time doing so. I have used the method described here to learn how to define custom hash functions. I tried removing all the const since I felt that might be the cause of this problem but it led to other problems.

Here is the 3 errors the above code gives in Visual Studio 2022. enter image description here

Can someone kindly explain to me what is going on here and how do I define the hash function properly.

  • Your `operator()` should also be `const` – Yksisarvinen Sep 04 '22 at 09:49
  • @Yksisarvinen I tried both `bool const operator==(const A& other) const { return num == other.getNum(); }` and `const bool operator==(const A& other) const { return num == other.getNum(); }` and none of them changed anything. I dont understand what you mean. – Chandrachur Mukherjee Sep 04 '22 at 09:51
  • @ChandrachurMukherjee See [working demo](https://godbolt.org/z/zof4sYhh5). I've just added `const`. – Jason Sep 04 '22 at 09:55
  • 1
    `A` class is fine, but in you `std::hash` specialization, you have `size_t operator()(const A& key)`. This should be `size_t operator()(const A& key) const`. – Yksisarvinen Sep 04 '22 at 09:56

0 Answers0