包装散列函数返回包装类型的散列

问题描述

我有以下代码

#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)};
}

基本上,这个想法是我有一个围绕模板类型的包装器,我希望能够在 unordered_set/map 中使用这个包装器类。但我收到以下错误no match for call to '(std::hash<int>) (const g<int>&)'。这很奇怪——c++ 没有实现这个哈希吗?我做错了什么?

解决方法

您的代码试图在 std::hash<int>() 上调用 t,其类型为 g<int>。您需要“解开”包装器并在封闭的 std::hash<int>() 上调用 int

return std::hash<E>()(t.val);