reinterpret_cast<无符号长>无效的强制转换
reinterpret_cast<unsigned long> Invalid Cast
我正在使用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 long
比int
长的64位x86平台上将做一些坏事。
根据C++标准(5.2.10重新解释铸件)
2 interpret_cast运算符不应丢弃constness(5.2.11).积分、枚举、指针或指向成员类型的指针可以显式转换为其自己的类型;这样的强制转换产生其操作数的值
请改用static_cast
。
相关文章:
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- is_same和variadic模板编译时错误无效转换
- 如何将常量无效*转换为istream?
- 无效* 转换获得意外输出
- 无法确定为什么函数调用中从 char* 到 char 的无效转换
- 在这个简单函数中从'char'到'const char*'的无效转换
- C++从 'const char*' 到 'char*' Arduino Uno 的无效转换
- 如何修复C++中的"错误:从'int'到'const char*'[-fallowive]的无效转换?
- C 错误:从(基类模板)到子类的无效转换
- 如何将常量无效*转换为无符号字符*
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 常量正确性编译错误到模板函数中的无效转换错误
- 从"char"到"const char*"的无效转换[-fpermissive](idk why)
- 从“ void*”到“ pthread_t*”的无效转换
- 当函数调用时,试图阻止数组更改时发生无效转换错误
- 使用基类中定义的函数返回指向派生类实例的指针时发生无效转换错误
- C++从字符到常量字符*的无效转换
- ALL_OF从'char'到'const char*'的无效转换 [-允许]
- C和C++上的无效转换错误
- C++ 在模板专用化中从 strcmp() 中的 'char' 到 'const char*' 的无效转换