我正在用 C++ 实现一个 HashTable
模板类,它的原型(prototype)是这样的:
template<class K, class T, unsigned int containerSize=CONTAINER_SIZE>
class LPHashTableChained{
........
unsigned int hashFunction(K& key);
}
我的问题是,当 K
等于字符串类型时,我如何才能专门化我的 hashFunction()
方法以表现不同。
我尝试以正确的格式和第二个实现来实现该函数,其中我省略了 class K
参数并将字符串作为如下类型:
第一次实现:
template<class K, class T, unsigned int containerSize>
unsigned int LPHashTableChained<K,T,containerSize>::hashFunction(K& key){
}
第二次实现:
template<class T, unsigned int containerSize>
unsigned int LPHashTableChained<string,T,containerSize>::hashFunction(const string& key){
}
但是我得到了编译错误!!!
当 K= string
时,指定此 hashFunction
的最简单方法是什么???
谢谢
最佳答案
您不能部分特化模板的成员函数。 (不过,总特化很好。)
不过,对于您的类来说,最好的方法是像标准库那样做,并将散列函数作为“策略”类型的模板参数提供:
template <typename K, typename V, typename Hash = std::hash<K>>
class HashTable
{
Hash hasher;
// use hasher(x)
};
现在您可以简单地为您的字符串类型专门化哈希器,或者提供您自己的:
// 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;
关于c++ - 如何在具有多种参数类型的模板类中仅专门化一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8278135/