I have the following code:
#include <bits/stdc++.h>
using namespace std;
// wrapper class on type E
template <typename E>
class g {
public:
E val;
g(E x) : val(x) {};
};
// hash for g<E> should be hash for E
template<typename E> struct std::hash<g<E>> {
std::size_t operator()(const ::g<E> &t) const {
return std::hash<E>()(t);
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
unordered_set<g<int>>{g<int>(3)};
}
Basically, the idea is that I have a wrapper around a templated type, and I want to be able to use this wrapper class in an unordered_set/map. But I get the following error:
no match for call to '(std::hash<int>) (const g<int>&)'
. This is strange - doesn't c++ implement this hash? What am I doing wrong?
Your code is attempting to invoke std::hash<int>()
on t
, which has type g<int>
. You need to "unwrap" the wrapper and call std::hash<int>()
on the enclosed int
:
return std::hash<E>()(t.val);