gpt4 book ai didi

c++ - 枚举的 reinterpret_cast 错误

转载 作者:可可西里 更新时间:2023-11-01 14:57:01 25 4
gpt4 key购买 nike

为什么我不能对这样的转换使用 reinterpret_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);
}

最佳答案

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-enumenum-to-int 转换不在列表中:

  • 指向整数类型的指针,只要整数大到足以容纳它
  • nullptr_t 到整数
  • 整型或枚举指针
  • 指向不同类型的另一个函数指针的函数指针
  • 指向不同类型的另一个对象指针的对象指针
  • nullptr_t 到其他指针类型
  • T1 的情况下,
  • T1 的指向成员的指针指向 T2 的不同指向成员的指针T2 是对象或函数

reinterpret_cast 通常用于告诉编译器:嘿,我知道你认为这个内存区域是一个 T,但我希望你将它解释为U(其中 TU 是不相关的类型)。

还值得注意的是,reinterpret_cast 会对位产生影响:

5.2.10.3

[ 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

关于c++ - 枚举的 reinterpret_cast 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12228562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com