How to implement a generic hash function in C++

algorithm, c++, hashtable, string

Solution

You would typically use `std::hash` for this, and let type implementors specialize that template as required.

size_t key_hash = std::hash<T1>()(key);

There is no way you can generically implement a hash function for any random type you are given. If two objects are equal, their hash codes must be the same. You could simply run the raw memory of the objects through a hash function, but the types might implement an `operator==` overload that ignores some piece of object data (say, a synchronization object). In that case you could potentially (and very easily) return different hash values for equal objects.

Problem

I am trying to implement HashTable in C++ via templates. Here is the signature: ``` template<class T1, class T2> class HashTable { public: void add(T1 a, T2 b); void hashFunction(T1 key, T2 value) { // how to implement this function using key as a generic // we need to know the object type of key } }; ``` So, I am unable to move ahead with implementation involving a generic key. In Java, I could have easily cast the key to string and then be happy with implementing the hash for a key as string. But, in C++, what I know is that there is a concept of RTTI which can dynamically cast an object to the desired object. How to implement that dynamic cast, if this method is correct at all? If using template is not the correct approach to implement generics for this case, then please suggest some better approach.

Original source