We are trying to set mHashCode
either through template specialization of operator()
(string in this case) or through the c'tor of HashFunction()
by the user provided key(here, inKey
).
#include <iostream>
#include <unordered_map>
using namespace std;
template< class Key > class HashFunction
{
public:
HashFunction( const Key & k );
inline operator unsigned() const
{
return mHashCode;
}
size_t operator()(const Key &k) const;
private:
unsigned mHashCode;
};
template<> HashFunction< string >::HashFunction( const string & k )
{
mHashCode=std::hash<string>{}(k);
}
template <> size_t HashFunction< string >::operator()(const string &k) const
{
return mHashCode;
}
template< class Key, class Val, class Hash = HashFunction< Key > >
class unordered_map_wrapper
{
public:
unordered_map_wrapper();
private:
unordered_map<Key, Val, Hash> * mTable;
};
template< class Key, class Val, class Hash >
unordered_map_wrapper< Key, Val, Hash >::unordered_map_wrapper()
{
mTable=new unordered_map<Key, Val, Hash>(5);
}
int main() {
unordered_map_wrapper<string, unsigned> h;
return 0;
}
If the user is passing the hash function(not match with string
, unsigned
etc.) along with the hash()
constructor, this mHashCode
is generated by hitting the c'tor of HashFunction()
. An object of HashFunction
class will be created in this case. Due to this reason, mHashCode
will generate and default template specialization of operator()
will get control and return mHashCode
. i.e. it's returning user's value only.
Template specialization is using operator unsigned()
(specilization of constructor), creating an object and returning mHashCode
.
Its working fine if we are passing hash function with the help of template argument and by default, it's using operator(), not the c'tor of HashFunction()
. Getting a compile time error if we are using c'tor like the above snippet.
How could we set mHashCode
through this c'tor so that user can use std::Hash()
? Our hard requirement is that we need to invoke std::hash()
through c'tor, not through the operator.
Thanks in advance!