【问题标题】:Why is there a mistake in class specialization?为什么班级专业化会出现错误?
【发布时间】:2020-04-28 10:18:02
【问题描述】:

我正在尝试用 C++ 实现字典,但是当我定义类哈希的特化时,我得到了错误:

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

这里是代码

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);
  }
};

可能是什么问题?

【问题讨论】:

  • 显示的代码没有明显的原因导致您报告的错误消息。请参阅this example,它编译得很好。问题可能在于您使用hash 的方式或位置。
  • 注意:const string the_key 应该是 const string &amp; the_key 以避免制作不必要的副本,您可能只使用 size_t 代替 hash_valuelengthi 以避免任何类型的演员表.

标签: c++ dictionary data-structures hash hashtable


【解决方案1】:

这应该可以工作,除了您的代码中可能有using namespace std,这会导致您的hash 模板与std 模板冲突。删除它,问题就会消失。

【讨论】:

  • 非常感谢,这就是问题所在!如果我使用命名空间 std,为什么会发生冲突?
  • @Tony9999 using namespace std 告诉编译器在命名空间std 中查找非限定名称。因此,当您稍后引用hash 时,您自己的::hashstd::hash 都会找到。
  • 完美,我明白了。我不知道 std::hash 也存在
  • @Tony9999 有点羞耻——很少有人知道潜伏在std 中的一切——但这是不去using namespace std; 的主要原因之一补充说今天有效的东西明天可能是一个神秘的错误。
猜你喜欢
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多