user3483203
user3483203

Reputation: 51175

Using separate functions based on template class type

I have a fairly simple assignment to review hash tables, and we have to create a template class and test it using floats, ints, and STL strings as key data types.

I have the class setup like so:

 template<class K, class T>
 class hashTable{
     public:
     private:
 };

When I call the class to test it, I use:

hashTable<float, data>
hashTable<int, data>

etc... I just am not sure how to make the class use the hash function I have for each data type based on what data type I use when I call the function.

Upvotes: 0

Views: 49

Answers (2)

NathanOliver
NathanOliver

Reputation: 181027

I would suggest you do it like the standard does. Add a template parameter for the hash function and then use the standard hash. If you have a custom type that the standard hash does not work for then you can implement you own and include it in the template arguments.

template<class K, class T, class Hash = std::hash<K>>
class hashTable{ 
// stuff 
};

Upvotes: 0

Petr
Petr

Reputation: 10007

I see at least three approaches:

First. Create an overloaded function hash for all your types:

hash_t hash(int);
hash_t hash(float);

and in hashTable just call hash().

Second. Create a separate templated class (or, well, a function) hash<T> and specialize it for int, float, etc. Then in hastTable refer to it in general way as hash<K>:

 template<class T> class hash;
 template<> class hash<int> { hash_t operator() {...} };
 template<> class hash<float> { hash_t operator() {...} };

Third. Supply the needed class or function via a template parameter to hashTable, just the way the standard std::sort received comparison function:

template<class K, class T, class Hash>
class hashTable...

Upvotes: 1

Related Questions