reinterpret_cast<无符号长>无效的强制转换

reinterpret_cast<unsigned long> Invalid Cast

本文关键字:无效 转换 gt 无符号 cast lt reinterpret      更新时间:2023-10-16

我正在使用C++中的哈希表。散列函数:

// 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声明为:时

HashTable<int, std::string> hmap;

其显示:

从"int"类型到"unsigned_long_int"的强制转换无效

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

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

如果你的目标是真正"重新解释位模式",那么你必须转换到引用。也就是说,如果x是类型为int的左值,则reinterpret_cast<unsigned long&>(x)是有效的。但现在您正进入危险的领域,因为这通常是未定义的行为,并且可能在32位x86平台上工作,但在unsigned longint长的64位x86平台上将做一些坏事。

根据C++标准(5.2.10重新解释铸件)

2 interpret_cast运算符不应丢弃constness(5.2.11).积分、枚举、指针或指向成员类型的指针可以显式转换为其自己的类型;这样的强制转换产生其操作数的值

请改用static_cast