问题描述
为什么我不能使用reinterpret_cast操作符进行这样的转换?
Why i can't use reinterpret_cast operator for such a cast?
enum Foo { bar, baz };
void foo(Foo)
{
}
int main()
{
// foo(0); // error: invalid conversion from 'int' to 'Foo'
// foo(reinterpret_cast<Foo>(0)); // error: invalid cast from type 'int' to type 'Foo'
foo(static_cast<Foo>(0));
foo((Foo)0);
}
推荐答案
这是一个常见的误解。可以使用 reinterpret_cast
执行的转换在标准的5.2.10中明确列出。 int
-to - 枚举
和枚举
-to- int
转换不在列表中:
That is a common misconception. Conversions which can be performed with reinterpret_cast
are listed explicitly in 5.2.10 of the standard. int
-to-enum
and enum
-to-int
conversions are not in the list:
- 指向整数类型的指针,只要整数是足够大的,以保持它
-
nullptr_t
整数 - 整数型或
枚举
指向 - 函数指向不同类型的另一个函数指针的指针
- 指向另一个的对象指针不同类型的对象指针
-
nullptr_t
到其他指针类型 - 指针到成员在
T1
到T2
的另一个指针成员,如果T1
和T2
是对象或函数
- Pointer to integral type, so long as the integer is large enough to hold it
nullptr_t
to integer- integral type or
enum
to pointer - function pointer to another function pointer of different type
- object pointer to another object pointer of different type
nullptr_t
to other pointer type- pointer-to-member of
T1
to a different pointer-to-member ofT2
in cases where bothT1
andT2
are objects or functions
reinterpret_cast
通常用于告诉编译器:嘿,我知道你认为这个内存区是一个 T
,但我'你喜欢你把它解释为一个 U
(其中 T
和 U
是不相关的类型)
reinterpret_cast
is typically used to tell the compiler: Hey, I know you think this region of memory is a T
, but I'd like you to interpret it as a U
(where T
and U
are unrelated types).
还值得注意的是, reinterpret_cast
可以对这些位有影响:
It is also worth noting that reinterpret_cast
can have effects on the bits:
[注意:reinterpret_cast执行的映射可能,或者可能不会从原始值产生一个代表性。 - 结束笔记]
[ Note: The mapping performed by reinterpret_cast might, or might not, produce a representation dif- ferent from the original value. — end note ]
C风格的转换始终可以工作,因为它包含 static_cast
在尝试。
The C-style cast always works, because it included static_cast
in its attempts.
这篇关于enum的reinterpret_cast错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!