如何在具有许多参数类型的模板类中专门使用一个方法

Lam*_*rou 1 c++ templates class

我正在HashTable用C++ 实现一个模板类,它的原型是这样的:

template<class K, class T, unsigned int containerSize=CONTAINER_SIZE>
class LPHashTableChained{
    ........

    unsigned int hashFunction(K& key);

}
Run Code Online (Sandbox Code Playgroud)

我的问题是,hashFunction()K等于字符串类型时,我如何专门化我的方法以表现不同.

我尝试用正确的格式实现函数,并使用第二个实现,我省略了class K参数并将字符串作为类型如下所示:

第一次实施:

template<class K, class T, unsigned int containerSize>
unsigned int LPHashTableChained<K,T,containerSize>::hashFunction(K& key){

}
Run Code Online (Sandbox Code Playgroud)

第二次实施:

template<class T, unsigned int containerSize>
unsigned int LPHashTableChained<string,T,containerSize>::hashFunction(const string& key){

}
Run Code Online (Sandbox Code Playgroud)

但我得到编译错误!

什么是specilize最简单的方法hashFunction,当K= string???

谢谢

Ker*_* SB 5

您不能部分专门化模板的成员函数.(但是,专业化总数很好.)

然而,您的类的最佳方法是按照标准库的方式执行,并将哈希函数作为"策略"类型模板参数提供:

template <typename K, typename V, typename Hash = std::hash<K>>
class HashTable
{
  Hash hasher;
  // use hasher(x)
};
Run Code Online (Sandbox Code Playgroud)

现在您可以简单地为您的字符串类型专门设置hasher,或者提供您自己的:

// provide custom

struct MyInsaneHasher { std::size_t operator()(const Foo &) const; };
HashTable<Foo, int, MyInsaneHasher> m1;

// add specialization for `std::hash`:

namespace std
{
  template <> struct hash<Bar> { size_t operator()(const Bar&) const; };
}
HashTable<Bar, int> m2;
Run Code Online (Sandbox Code Playgroud)