如何为各种模板类型构建哈希函数?

How to build hash function for various template types?

我正在练习构建一个可以使用 template 接受不同类型的哈希表。

如何实现 hashFunction 在编译时不知道类型?

template<class K, class V>
class HashTable {
  public:
  vector<vector<Bucket<K, V> > > table;
  ...
  size_t hashFunction(const K &k) {
    //can't implement without knowing the runtime types
  }
}

我想我应该做类似的事情:

return hash<K>(k) % table.size();

更新:

感谢 R Sahu 的回答,现在我知道这是我不清楚的模板部分专业化部分。请参阅 this question and this link 以供参考。

How do I implement hashFunction not knowing the types at compile time?

您可以使用通用逻辑为所有类型生成哈希值。将构成 k 的字节视为字符串中的字符。

此外,为用户提供提供自己的哈希函数的能力。

// Generic implementation
template <typename K> struct Hash
{
   static size_t get(const K& k)
   {
      ...
   }
};

template<class K, class V, typename HashGenerator = Hash<K>>
class HashTable {
  public:
  vector<vector<Bucket<K, V> > > table;
  ...
  size_t hashFunction(const K &k) {
     HashGenerator::get(k);
  }
}

struct Foo { ... };

// Specialize Hash for Foo.
template <> struct Hash<Foo>
{
   static size_t get(const Foo& foo)
   {
      ...
   }
}