unordered_map 类的签名是这样的:
template<class Key,
class Ty,
class Hash = std::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, Ty> > >
class unordered_map;
您的示例有效,因为默认的 Pred,std::equal_to<>,默认情况下使用 operator== 检查相等性。编译器找到您的 foo::operator== 成员函数并使用它。
std::hash 没有任何可以调用类上的成员函数的专业化,因此您不能只使用自定义哈希将成员添加到 foo 。您将需要专门化 std::hash 。如果您希望它在 foo 上调用成员函数,请继续。你最终会得到这样的东西:
struct foo
{
size_t hash() const
{
// hashing method here, return a size_t
}
};
namespace std
{
// Specialise std::hash for foo.
template<>
class hash< foo >
: public unary_function< foo, size_t >
{
public:
size_t operator()( const foo& f )
{
return f.hash();
}
};
}