3 ms·
This bugs me as well, since there still isn't a general enough official solution, even with C++20's bit_cast. Unofficially, the C way of type punning(pointer co
by indigoabstract 3y ago
This bugs me as well, since there still isn't a general enough official solution, even with C++20's bit_cast. Unofficially, the C way of type punning(pointer conversions and unions) still works in probably all C++ compilers, but it's UB, so potentially dangerous.
I think most use cases for type punning fall in 2 categories: conversions between types with same size in memory, for writing or reading as a new type(ex. read an f32 as an u32) or accessing only a part of the data, like the first or the last 2 bytes in a u32.
Ideally, there would be a way to specify that a union is used for type punning and what conversion types are allowed (using something similar to concepts or constraints). That would probably solve most use cases and also allow the compiler to easily detect it.