2014-08-30 90 views
0

我正在使用C++中的散列表。散列函数:reinterpret_cast <unsigned long>无效的投射

// Default hash function class 
template <typename K> 
struct KeyHash { 
    unsigned long operator()(const K& key) const { 
     return reinterpret_cast<unsigned long>(key) % TABLE_SIZE; 
    } 
}; 

后来,当我宣布哈希表:

HashTable<int, std::string> hmap; 

其显示:

从 '廉政' 类型 'unsigned_long_int'

无效的转换

这里有什么问题reinterpret_cast<unsigned long>

+0

也许是'sizeof(unsigned long)!= sizeof(int)',所以“重新解释位模式”可能没有意义......我不确定。 – 2014-08-30 19:25:42

+0

这个****是谁给的那个downvote?所以每个人都不会像你一样了解所有事情。 – 2014-08-30 19:27:55

+0

看来你是在假设我给了你那个downvote。我没有。 [证明](http://imgur.com/2tey48m)。 – 2014-08-30 19:29:39

回答

4

您不能reinterpret_cast两个整数类型之间的句点。这不是reinterpret_cast。如果要在两个整数类型之间进行转换,请使用static_cast

如果你的目标是真正“重新解释位模式”,那么你必须投到参考。即如果xint类型的左值,则reinterpret_cast<unsigned long&>(x)有效。但是现在你正在进入危险区域,因为这通常是未定义的行为,并且可能在32位x86平台上工作,但是在64位x86平台上,unsigned long长于int会做一些坏事。

+0

+1和AC为一个很好的答案,而不是投降我(人们没有理由):) – 2014-08-30 19:39:59

+0

访问'reinterpret_cast (x)'的值是_always_ UB;演员只在语法上有效。 – ildjarn 2014-08-30 19:58:59

+0

它总是UB,但它仍然可能在某些实现上表现可预测,就像所有的UB一样。 – Brian 2014-08-30 20:09:11

2

根据C++标准(5.2.10重释铸造)

2 reinterpret_cast运算符不应抛弃常量性 (5.2.11)。 指针到成员类型的整数,枚举,指针或表达式可以显式转换为其自己的类型; 这样的演员会产生其操作数的值。

改为使用static_cast

+0

+1,但其他人已经被接受了,先生:) – 2014-08-30 19:41:37

相关问题