错误:'hash'不是一个类模板

3
#include <unordered_map>
#include <memory>
#include <vector>

template<> // Voxel has voxel.position which is a IVec2 containing 2 values, it also has a bool value
struct hash<Voxel> {  
size_t operator()(const Voxel & k) const  
    {  
        return Math::hashFunc(k.position);  
    }  
};  

template<typename T> // This was already given
inline size_t hashFunc(const Vector<T, 2>& _key)
{
    std::hash<T> hashfunc;
    size_t h = 0xbd73a0fb;
    h += hashfunc(_key[0]) * 0xf445f0a9;
    h += hashfunc(_key[1]) * 0x5c23b2e1;
    return h;
}

我的主要
int main()
{
    Voxel t{ 16,0,true };
    std::hash(t);
}

我现在正在撰写有关std::hash的专题。现在,在线提交页面总是返回我的代码以下错误。我不知道为什么以及我做错了什么。

error: 'hash' is not a class template struct hash<>

并且

error: no match for call to '(const std::hash<Math::Vector<int, 2ul> >)   (const Math::Vector<int, 2ul>&)' noexcept(declval<const_Hash((declval<const_Key&>()))>.

我自己的编译器只会抛出

error: The argument list for "class template" std :: hash "" is missing.

#include <unordered_map> #include <memory> #include <vector> - Fabian Patzlaff
仅翻译文本内容:仍然存在之前的错误,没有做任何更改。 - Fabian Patzlaff
2个回答

9
为了后人能看懂,我在忘记包含#include <functional>时遇到了同样的错误信息。

5

您正在全局命名空间中专门化std::hash<>,这是不合法的。

专门化必须在相同的命名空间std中声明。请参见std::hash的示例:

// custom specialization of std::hash can be injected in namespace std
namespace std
{
    template<> struct hash<S>
    {
        typedef S argument_type;
        typedef std::size_t result_type;
        result_type operator()(argument_type const& s) const
        ...

谢谢。这消除了大部分错误,只剩下错误:no match for call to '(const std::hash<Math::Vector<int, 2ul> >) (const Math::Vector<int, 2ul>&)' noexcept(declval<const _Hash&>()(declval<const _Key&>()))>。 - Fabian Patzlaff
@FabianPatzlaff,你的代码不完整,这可能是为什么你的问题被投票降低的原因。请发布一个“最小化、完整化和可验证”的示例。 - Maxim Egorushkin
@FabianPatzlaff,这个错误可能是因为您没有包含std::hash<Voxel>的特化头文件。 - Maxim Egorushkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接