简体   繁体   English

如何为模板类实现std :: hash

[英]How to implement std::hash for a template class

I have a template class looking like this: 我有一个模板类,看起来像这样:

template <int N, class TypeId> class Indexer {
...
}

and I want to use it in std::unordered_map , I need a hash function. 我想在std::unordered_map使用它,我需要一个哈希函数。 In the codebase we already had something similar (but on an untemplated class) so I tried to do it like this: 在代码库中,我们已经有一些类似的东西(但是在未模板化的类上),所以我尝试这样做:

namespace std {
template <int N, class TypeId>
struct hash<Indexer<N, TypeId> > {
    size_t operator()(const Indexer<N, TypeId>& id) const noexcept {
        ...
    }
};
}

It is also quite similar to another answer . 它也非常类似于另一个答案 Unfortunately this does not work, just gives a bunch of unhelpfull errors. 不幸的是,这是行不通的,只是给出了一系列无法​​解决的错误。 Any insights? 有什么见解吗?

It looks like you're missing a semi-colon at the end of the definition of the Indexer class. 看来您在Indexer类的定义末尾缺少分号。

This works: 这有效:

#include <functional>

template <int N, class TypeId> struct Indexer {};

namespace std {
template <int N, class TypeId>
struct hash<Indexer<N, TypeId> > {
   size_t operator()(const Indexer<N, TypeId>& id) const noexcept { return 0; }
};
}

int main() {
   return 0;
}

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

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