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);
}
That is a common misconception. Conversions which can be performed with
reinterpret_castare listed explicitly in 5.2.10 of the standard.int-to-enumandenum-to-intconversions are not in the list:nullptr_tto integerenumto pointernullptr_tto other pointer typeT1to a different pointer-to-member ofT2in cases where bothT1andT2are objects or functionsreinterpret_castis typically used to tell the compiler: Hey, I know you think this region of memory is aT, but I’d like you to interpret it as aU(whereTandUare unrelated types).It is also worth noting that
reinterpret_castcan have effects on the bits:The C-style cast always works, because it included
static_castin its attempts.