0

I have a simple question so as you can see I have a hash function that returns a long and takes in a K key. This K is a typename in my template class HashTable, my hash function is not all-type encompassing so I need to do function overloading on my function hashfct based on what type K is. How do I specialize the K key if it is a parameter of the function hashfct? In other words, what is the syntax for specializing K key in this specific case where it is a function parameter?

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

long hashfct(K key)
{
//Code goes here...
}
  • When you call `hashfct(key)` the , the correct overload for `K` is automatically selected according to the type of `key`. Any error you have encountered so far? – ph3rin Oct 06 '19 at 06:02
  • @KaenbyouRin I guess I phrased the question wrong but I want specialize the K key so that the overload is only called for example when key is of char type but not any other type. –  Oct 06 '19 at 06:06

1 Answers1

1

Use 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;
}

As a side note, you can use or specialize std::hash (for specializing std::hash see this question).

ph3rin
  • 4,426
  • 1
  • 18
  • 42
  • Thanks for the help. Greatly appreciated! I should of realized I could of just done that lol. –  Oct 07 '19 at 03:10