无法解析符号哈希
symbol hash could not be resolved
我有这样的class
#ifndef _OBJECT_H_
#define _OBJECT_H_
#include <iostream>
#include <functional>
namespace core {
class Object {
protected:
template <>
struct std::hash<core::Object>
{
size_t operator()(const core::Object &x) const = 0;
};
public:
virtual Object* clone() = 0;
virtual int hashCode() = 0;
virtual std::string getClass() = 0;
virtual ~Object();
};
}
#endif
我想强制所有继承的 classes 实现 hash
计算并提供使用实现的方法获得 hashcode
的能力以覆盖 hash
中的 ()
] 结构。
但是我的编译器显示 Symbol 'hash' could not be resolved
错误。
我将 Eclipse c++
与 CDT
插件和 TDM gcc 5.1.0
一起使用。有什么问题吗?
如果要为 Object
添加显式特化到 std::hash
,正确的方法是:
namespace core {
class Object { ... };
}
namespace std {
template <>
struct hash<core::Object> {
size_t operator()(const core::Object& x) const {
return x.hashCode(); // though to make this work,
// hashCode() should be const
}
};
}
显式特化必须在命名空间范围内 - 特别是在 std
的范围内。而且你只能使 virtual
函数成为纯函数(= 0
),这个不应该是虚函数或纯函数。
旁注,您的 _OBJECT_H
include guard 是 reserved identifier。你应该选择另一个。
我有这样的class
#ifndef _OBJECT_H_
#define _OBJECT_H_
#include <iostream>
#include <functional>
namespace core {
class Object {
protected:
template <>
struct std::hash<core::Object>
{
size_t operator()(const core::Object &x) const = 0;
};
public:
virtual Object* clone() = 0;
virtual int hashCode() = 0;
virtual std::string getClass() = 0;
virtual ~Object();
};
}
#endif
我想强制所有继承的 classes 实现 hash
计算并提供使用实现的方法获得 hashcode
的能力以覆盖 hash
中的 ()
] 结构。
但是我的编译器显示 Symbol 'hash' could not be resolved
错误。
我将 Eclipse c++
与 CDT
插件和 TDM gcc 5.1.0
一起使用。有什么问题吗?
如果要为 Object
添加显式特化到 std::hash
,正确的方法是:
namespace core {
class Object { ... };
}
namespace std {
template <>
struct hash<core::Object> {
size_t operator()(const core::Object& x) const {
return x.hashCode(); // though to make this work,
// hashCode() should be const
}
};
}
显式特化必须在命名空间范围内 - 特别是在 std
的范围内。而且你只能使 virtual
函数成为纯函数(= 0
),这个不应该是虚函数或纯函数。
旁注,您的 _OBJECT_H
include guard 是 reserved identifier。你应该选择另一个。