为什么 class 专业化有错误?
Why is there a mistake in class specialization?
我试图用 C++ 实现字典,但是当我定义 class 散列的特化时,我得到了错误:
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);
}
};
可能是什么问题?
这应该有效,除了您的代码中可能有 using namespace std
,这会导致您的 hash
模板与标准模板冲突。删除它,问题就会消失。
我试图用 C++ 实现字典,但是当我定义 class 散列的特化时,我得到了错误:
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);
}
};
可能是什么问题?
这应该有效,除了您的代码中可能有 using namespace std
,这会导致您的 hash
模板与标准模板冲突。删除它,问题就会消失。