简体   繁体   English

我可以覆盖std :: hash吗?

[英]Can I override std::hash?

I can replace the actual implementation of std::hash with my own definition of std::hash in C++ 11 ? 我可以用我自己在C ++ 11中定义的std::hash替换std::hash的实际实现吗?

I mean from my codebase, without touching the standard library. 我的意思是从我的代码库,而不是触及标准库。

I can't see any use for virtual function/polymorphism in this case, so I suppose that I can't alter the definition of std::hash anyway ? 在这种情况下,我看不出任何虚函数/多态的用法,所以我想我无法改变std :: hash的定义?

You can specialise hash for specific types. 您可以为特定类型专门化哈希。 See here and here eg like this 看到这里这里,例如像这样

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

If you think you can do better than the library implementors for existing versions you are either 1. wrong or 2. clever 如果您认为您可以比现有版本的库实现者做得更好,那么您可能是1.错误或2.聪明

Yes it's okay, and you don't have to modify the standard library in any way, just use template specialization: 是的没关系,您不必以任何方式修改标准库,只需使用模板专业化:

namespace std
{
    template<>
    struct hash<YourSpecialType>
    {
        // ...
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM