简体   繁体   English

如何仅专门化具有多个参数类型的模板类中的一种方法

[英]How to specialize ONLY one method inside a template class with many argument types

I am implementing a HashTable template class in C++ and its prototype is like this: 我正在用C ++实现HashTable模板类,其原型如下:

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

    unsigned int hashFunction(K& key);

}

My question is how I can specialize my hashFunction() method to behave differently when K equals string type. 我的问题是,当K等于字符串类型时,如何专门化hashFunction()方法以表现不同。

I tried to implement the function with its correct format and with a second implementation where I omit the class K argument and put string as the type like below: 我尝试以正确的格式实现该功能,并尝试第二种实现,其中省略了class K参数,并将string设置为如下类型:

1st implementation: 第一种实现:

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

}

2nd implementation: 第二实施:

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

}

But I get compilation errors !!! 但是我得到编译错误!

What is the easiest way to specilize this hashFunction when K= string ??? K= string时,指定此hashFunction的最简单方法是什么?

Thanks 谢谢

You cannot partially specialize member functions of templates. 您不能部分专门化模板的成员函数。 (Total specializations are fine, though.) (不过,总的专业水平很好。)

The best approach for your class is to do as the standard library does, though, and provide the hash function as a "policy"-type template argument: 不过,对您的类而言,最好的方法是像标准库那样做,并提供散列函数作为“策略”类型的模板参数:

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

Now you can simply specialise the hasher for your string type, or provide your own: 现在,您只需为字符串类型专门设置哈希器,或者提供自己的哈希器:

// 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;

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

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