【发布时间】:2015-08-23 15:26:47
【问题描述】:
我想为我的自定义类型 AnimationSet 重载 std::hash 模板:
struct AnimationSet {
const AnimationData *animationData;
SceneNode *sceneNode;
bool operator==(const AnimationSet &other) const {
return ( this->animationData == other.animationData &&
this->sceneNode == other.sceneNode );
}
};
如您所见,它是一个仅包含两个指针的结构。
将这些指针转换为 unsigned int 以计算 AnimationSet 的哈希值是否合法?
namespace std {
template<>
struct hash<AnimationSet> {
size_t operator()(const AnimationSet &set) const {
hash<unsigned int> h;
return h((unsigned int)set.animationData) ^ h((unsigned int)set.sceneNode);
}
};
}
编辑: 我在哈希重载的背景下问这个问题,但我想知道更一般问题的答案:“将任何指针强制转换为 unsigned int 是否公平?”
【问题讨论】:
-
关于您的“一般性问题”,请参考this。
-
std::hash已经专门用于指针,因此您无需转换即可进行散列。可以直接使用hash<const AnimationData *>和hash<SceneNode *>。
标签: c++