我正在使用C++中的Hashtable.哈希函数:
// Default hash function class
template <typename K>
struct KeyHash {
unsigned long operator()(const K& key) const {
return reinterpret_cast<unsigned long>(key) % TABLE_SIZE;
}
};
Run Code Online (Sandbox Code Playgroud)
然后,当我声明哈希表为:
HashTable<int, std::string> hmap;
Run Code Online (Sandbox Code Playgroud)
它显示:
从'int'类型到'unsigned_long_int'的无效转换
这是什么问题reinterpret_cast<unsigned long>?
你不能reinterpret_cast介于两种整数类型之间.这不是reinterpret_cast为了什么.如果要在两种整数类型之间进行转换,请使用static_cast.
如果你的目标是真正"重新解释位模式",那么你将不得不转向参考.也就是说,reinterpret_cast<unsigned long&>(x)如果x是类型的左值,则有效int.但是现在你进入了危险的领域,因为这通常是未定义的行为,并且可能在32位x86平台上工作,但是在64位x86平台上会有unsigned long更长的时间int.