dwschrute
dwschrute

Reputation: 104

How to build hash function for various template types?

I'm practice building a hashtable that can accept different types using template.

How do I implement hashFunction not knowing the types at compile time?

template<class K, class V>
class HashTable {
  public:
  vector<vector<Bucket<K, V> > > table;
  ...
  size_t hashFunction(const K &k) {
    //can't implement without knowing the runtime types
  }
}

I'm guessing I should do something similar like:

return hash<K>(k) % table.size();

Update:

Thanks for R Sahu's answer, now I know it's the Template Partial Specialization part that I wasn't clear of. See this question and this link for reference.

Upvotes: 4

Views: 4183

Answers (1)

R Sahu
R Sahu

Reputation: 206747

How do I implement hashFunction not knowing the types at compile time?

You can have generic logic that can be used generate a hash value for all types. Treat the bytes that make up k like the characters in a string.

Also, provide the ability for the user to provide their own hash functions.

// Generic implementation
template <typename K> struct Hash
{
   static size_t get(const K& k)
   {
      ...
   }
};

template<class K, class V, typename HashGenerator = Hash<K>>
class HashTable {
  public:
  vector<vector<Bucket<K, V> > > table;
  ...
  size_t hashFunction(const K &k) {
     HashGenerator::get(k);
  }
}

struct Foo { ... };

// Specialize Hash for Foo.
template <> struct Hash<Foo>
{
   static size_t get(const Foo& foo)
   {
      ...
   }
}

Upvotes: 4

Related Questions