如何专门化用作函数参数的模板类型名?

How do I specialize a template typename being using as a function parameter?

我有一个简单的问题,如您所见,我有一个哈希函数,它 returns 很长并接受一个 K 密钥。这个 K 是我的模板 class HashTable 中的一个类型名,我的哈希函数不是包含所有类型的,所以我需要根据 K 的类型对我的函数 hashfct 进行函数重载。如果 K 键是函数 hashfct 的参数,我该如何特化它?换句话说,在作为函数参数的特定情况下,专门化 K 键的语法是什么?

template <typename K, V> class HashTable
{
//Code goes here...
}

long hashfct(K key)
{
//Code goes here...
}

使用template specialization:

template <typename KeyType>
long hashfct(KeyType key) = delete;

template <>
long hashfct<char>(char key) {
    return key;
}

int main() {
    int a = 0;
    char c = 'a';
    //hashfct(a);   //Compile error: hashfct<int>(int) is deleted
    hashfct(c);     //Ok, calls hashfct<char>(char)
    return 0;
}

作为旁注,您可以使用或专门化 std::hash (for specializing std::hash see this question)。