I tend to use a union for this. Something like:
template <class output_type, class input_type>
inline output_type punning_cast(const input_type& input)
{
union {
input_type in;
output_type out;
} u;
u.in = input;
return u.out;
}
Strictly speaking, this is Undefined Behavior in C++ (although not in C). But then so is yours, and I have yet to see a C++ compiler that does not "do what I want" for this construct... So I believe this is a fairly portable way to do type punning.
The best alternative, I think, is just to use memcpy
, and that is probably what I would do for the "pointer" version of your code. A good compiler will inline the call, so there should be no performance penalty.
I find the union
formulation easier to read.
[Update]
The GCC documentation says:
The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with
-fstrict-aliasing
, type-punning is allowed, provided the memory is accessed through the union type.
So GCC, at least, specifically supports using a union.