reinterpret_cast error for enum

前端 未结 2 1029
隐瞒了意图╮
隐瞒了意图╮ 2021-01-11 17:06

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 conversio         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-11 17:10

    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.

    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:

    • 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 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).

    It is also worth noting that reinterpret_cast can have effects on the bits:

    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 ]

    The C-style cast always works, because it included static_cast in its attempts.

提交回复
热议问题