I want to take a stack variable and reinterpret cast it into an unsigned integer type of the same size in bytes. For example, I might want to take double<
If you don't want to have undefined behavior due to violating the aliasing restrictions (C++11 3.10/10) then you need to access the object representations as characters:
template
int_type caster(const T& value) {
int_type v;
static_assert(sizeof(value) == sizeof(v), "");
std::copy_n(reinterpret_cast(&value),
sizeof(T),
reinterpret_cast(&v));
return v;
}
High quality compilers will optimize the copy away. E.g., this program:
int main() {
return caster(3.14f);
}
effectively optimizes to return 1078523331; on Intel processors.