0

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!

Foobar-naut
  • 123
  • 1
  • 1
  • 9
  • 1
    ... What even is the goal here? – cdhowie Mar 23 '17 at 18:35
  • A problem you are going to run into is that `HashFunction` is not default-constructible, which is required for it to be a stand-in for `std::hash`. There needs to be a `HashFunction()` constructor in order for you to use this type in this way. – cdhowie Mar 23 '17 at 18:44
  • A hash function needs to be able to hash more than one string. If you fix the hash code at construction it can't. – Alan Stokes Mar 23 '17 at 20:26
  • Can we use [something like](http://stackoverflow.com/questions/7222143/unordered-map-hash-function-c): `unordered_map, int> map = unordered_map, int>(1, *(new pairHash()));` 1 represents `size_type_Buskets`. – Foobar-naut Mar 24 '17 at 06:39

0 Answers0