diff --git a/cast.hpp b/cast.hpp index b6166a7d..89ca2cb6 100644 --- a/cast.hpp +++ b/cast.hpp @@ -18,6 +18,8 @@ #include #include +#include + namespace cruft::cast { /////////////////////////////////////////////////////////////////////////// @@ -222,4 +224,24 @@ namespace cruft::cast { cruft::debug::sanity (dst); return dst; } + + + /// Convert from SrcT to DstT by reinterpreting the bits that make up SrcT. + /// Effectively a reinterpret_cast of SrcT but without the undefined + /// behaviour. + /// + /// CXX#20: Convert instances of me to std::bit_cast when it becomes + /// available in supported compilers. + template + DstT + bit (SrcT &&src) + { + static_assert (sizeof (DstT) == sizeof (SrcT)); + static_assert (std::is_trivially_copyable_v>); + static_assert (std::is_trivially_copyable_v>); + + DstT dst; + std::memcpy (&dst, &src, sizeof (DstT)); + return dst; + } }