title: How to implement the hash function for the various type of key?
body: <p>I have implemented the hash map in C++.
  Everything works fine, except the hash function.</p>
  
  <p>I have a template class of the element so that I can use various variable types for the hash map.
  Here is my code for the element.</p>
  
  <pre><code>template &lt;class KeyType, class ValType&gt;
  class MapElem
  {
  public:
      typedef KeyType ktype;
      typedef ValType vtype;
  
      KeyType key;
      ValType val;
  
      MapElem* link;  // singly linked list
  };
  </code></pre>
  
  <p>And the hashfunction code.</p>
  
  <pre><code>template &lt;class HashMapElemType&gt;
  unsigned int 
  HashMap&lt;HashMapElemType&gt;::hashfunction(const KeyType k)
  {
      unsigned int hashIndex = 0;
  
  
  
      if (typeid(KeyType).name() == typeid(std::string).name())
      {
          unsigned int hashIndex = 0;
  
          const char* c = k.c_str();
  
          unsigned int i = 0;
          int index = 0;
          int shift = 0;
  
          while (c[index] != '\0')
          {
              if (shift == 32)
                  shift = 0;
              i += ((int) c[index++]) &lt;&lt; shift;
              shift += 8;
          }
  
          hashIndex = i;
      }
      else if (typeid(KeyType).name() == typeid(float).name())
      {   
          float f = k;
          hashIndex = (unsigned int) f;
      }
      else if (typeid(KeyType).name() == typeid(int).name())
      {
          int i = k;
          hashIndex = (unsigned int) i;
      }
      else
      {
          hashIndex = k;
      }
  
      hashIndex = hashIndex % divisor;
  
      return hashIndex;
  }
  </code></pre>
  
  <p>And there is a compile error for type casting in the hashfunction. I understand why the error occurs, but I don't know how to fix it.
  I wonder how to get a hash value from different types of key value.</p>
  
  <p>oh here is the error
  <a href="https://i.stack.imgur.com/eHEi4.jpg" rel="nofollow noreferrer">enter image description here</a></p>