8

std::hash我可以用我自己std::hash在 C++ 11 中的定义替换实际的实现吗?

我的意思是从我的代码库中,而不涉及标准库。

在这种情况下,我看不到虚函数/多态性的任何用途,所以我想我无论如何都不能改变 std::hash 的定义?

4

2 回答 2

9

您可以专门针对特定类型的哈希。见这里这里,例如这样

namespace std {
  template <> struct hash<Foo>
  {
    size_t operator()(const Foo & x) const
    {
      /* your code here, e.g. "return hash<int>()(x.value);" */
    }
  };
}

如果您认为您可以比现有版本的库实现者做得更好,那么您要么 1. 错误,要么 2. 聪明

于 2013-08-06T11:33:48.983 回答
7

是的,没关系,您不必以任何方式修改标准库,只需使用模板专业化:

namespace std
{
    template<>
    struct hash<YourSpecialType>
    {
        // ...
    };
}
于 2013-08-06T11:32:51.360 回答