std::bit-cast was introduced in the C++20 standard.
I know that reinterpret_cast is not suitable for this job due to type aliasing rules. However, why did they choose not to extend reinterpret_cast to treat the object like it bit sequence representation and preferred to give this functionality as a new language construct?
Well, there is one obvious reason: because it wouldn't do everything that
bit_castdoes. Even in the C++20 world where we can allocate memory at compile time,reinterpret_castis forbidden inconstexprfunctions. One of the explicit goals ofbit_castis to be able to do these sorts of things at compile-time:Now, you could say that you could just extend this specific usage of
reinterpret_casttoconstexprcontexts. But that makes the rules complicated. Instead of simply knowing thatreinterpret_castcan't be used inconstexprcode period, you have to remember the specific forms ofreinterpret_castthat can't be used.Also, there are practical concerns. Even if you wanted to go the
reinterpret_castroute,std::bit_castis a library function. And it's always easier to get a library feature through the committee than a language feature, even if it would receive some compiler support.Then there's the more subjective stuff.
reinterpret_castis generally considered an inherently dangerous operation, indicative of "cheating" the type system in some way. By contrast,bit_castis not. It is generating a new object as if by copying its value representation from an existing one. It's a low-level tool, but it's not a tool that messes with the type system. So it would be strange to spell a "safe" operation the same way you spell a "dangerous" one.Indeed, if you did spell them the same way, it starts raising questions as to why this is reasonably well-defined:
But this is somehow bad:
And sure, a language lawyer or someone familiar with the strict aliasing rule would understand why the latter is bad. But for the lay person, if it is fine to use
reinterpret_castto do a bit-conversion, it is unclear why it is wrong to usereinterpret_castto convert pointers/references and interpret an existing object as a converted type.Different tools should be spelled differently.