enum的reinterpret_cast错误 [英] reinterpret_cast error for enum

查看:181
本文介绍了enum的reinterpret_cast错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用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 可以用于所有类型的转换,因为它强制任何类型转换为另一种类型,具有此转换的所有副作用。

I think that reinterpret_cast can be use for all types of casts, because it's force any type casts to another type with all side-effects of this conversion.

这是一个常见的误解。可以使用 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 of T2 in cases where both T1 and T2 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:


5.2.10.3

[注意: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错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆