Based on the answers here I made a modern "pseudo-cast" function for ease of application.
C99 version
(while most compilers support it, theoretically could be undefined behavior in some)
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
union { U from; T to; } __x = {x};
return __x.to;
}
Universal versions
(based on the accepted answer)
Cast types with the same size:
#include <cstring>
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
static_assert(sizeof(T) == sizeof(U), "pseudo_cast can't handle types with different size");
T to;
std::memcpy(&to, &x, sizeof(T));
return to;
}
Cast types with any sizes:
#include <cstring>
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
T to = T(0);
std::memcpy(&to, &x, (sizeof(T) < sizeof(U)) ? sizeof(T) : sizeof(U));
return to;
}
Use it like:
float f = 3.14f;
uint32_t u = pseudo_cast<uint32_t>(f);
Update for C++20
C++20 introduces constexpr
std::bit_cast
in header <bit>
which is functionally equivalent for types with the same size. Nevertheless, the above versions are still useful if you want to implement this functionality yourself (supposed that constexpr
is not required), or if you want to support types with different sizes.
union A { float x; int32_t y; }; int32_t value = A{3.14f}.y;
the reason is, that the aliasing rule is never applied here. However, this trick only works up to C++11 (I think C++14 will change the rules so that this becomes UB).pseudo_cast
in C++ should alsostatic_assert
that both types are trivially copiable (seestd::is_trivially_copyable
).