I am trying to create a hashtable that handles generic objects. I would like to use the same hash algorithm for any type of object... Is there a way to do this with templates?
IE:
1 2 3 4
int HashTable::HashTable<T> hash( T obj )
{
//hash this 'obj' here...
}
and return an integer representing the bucket to put the object in...
How can I hash a generic object? I suppose I can do some kind of cast to get the bytes that make up the object, and hash those?
Yes, but you could read what boost approach is to get some ideas.
Boost sourcecode is well written and easy to understand
For its hash table boost requires that the user overloads a function which defines how hash values are evaluated: http://www.boost.org/doc/libs/1_44_0/doc/html/hash/custom.html
For its hash table boost requires that the user overloads a function which defines how hash values are evaluated:
I have reviewed the boost code and see how they do it - thanks (and your right - it does seem easy to follow).
I suppose I should be asking, is there a way to NOT have to overload anything about type T in order to hash it? I am hoping to not have to force the user to overload operators for T in order to hash it...
You cannot know in advance what would be relevant of user defined objects
EG: if you hash according to the object internal byte representation you will get unwanted result in the case that the object contains pointers or alike
Only the user would know how the object is represented and when two objects are considered to be different
Alright. I will then require the user to overload basic LT/GT ops...
I know in java there is a way to enforce that the type of object they attempt to construct a generic class with is (like T extends K, K extends T comparable or something of the such... Is there something similar in C++?
Not directly in the language. It was proposed to add this feature ( called 'concepts' ) in C++0x but it will come into the standard in a future revision.
You can however do something like that yourself or use (guess what?) boost concept check http://www.boost.org/doc/libs/1_44_0/libs/concept_check/concept_check.htm
All concepts would have done was to help simplify the template error messages given by the compiler. Concepts
did not really add any features to the language that aren't already there.