1

I'm trying to implement the dictionaries in C ++, but when I define the specialization of the class hash I get the error:

error: 'hash' is not a class template
error: template argument required for 'class hash'

Here is the code

template <class T>
class hash{
public:
  size_t operator()(const T the_key) const;
};


/* a specialization with type string */
template<>
class hash<string>
{
public:
  size_t operator()(const string the_key) const {
    unsigned long hash_value = 0;
    int length = (int) the_key.length();
    for (int i=0; i<length; i++)
      hash_value = 5 * hash_value + the_key.at(i);
    return size_t(hash_value);
  }
};

What could be the problem?

Tony9999
  • 25
  • 3
  • 1
    The code shown doesn't have an obvious cause for the error message you report. See [this example](https://godbolt.org/z/sdU2k3) which compiles fine. The problem is likely in how or where you use `hash`. – François Andrieux Jan 10 '20 at 18:33
  • 1
    Notes : `const string the_key` should be `const string & the_key` to avoid making needless copies and you could probably just use `size_t` for `hash_value`, `length` and `i` to avoid any kind of cast. – François Andrieux Jan 10 '20 at 18:34

1 Answers1

4

This should work, except that you probably had using namespace std in your code, which causes your hash template to conflict with the std one. Remove that, and the problem should go away.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thanks a lot, that was the problem! Why does it conflict if I use the namespace std? – Tony9999 Jan 10 '20 at 18:42
  • @Tony9999 `using namespace std` tells the compiler to look up unqualified names in namespace `std`. So, when you later reference `hash`, both your own `::hash` and `std::hash` are found. – Brian Bi Jan 10 '20 at 18:44
  • Perfect, I understand. I had no idea std::hash also existed – Tony9999 Jan 10 '20 at 18:47
  • 1
    One of the many reasons [`using namespace std` is considered a bad practice](https://stackoverflow.com/q/1452721/10957435). –  Jan 10 '20 at 19:00
  • 3
    @Tony9999 little shame in that--there are few people who know everything lurking in `std`--but this is one of the primary reasons not to `using namespace std;` The other big reason is stuff gets added so what works today could be a mystery bug tomorrow. – user4581301 Jan 10 '20 at 19:00