cast: add an approximate implementation of std::bit_cast

This commit is contained in:
Danny Robson 2020-10-27 15:30:40 +10:00
parent 6782b821b9
commit 98d8bd4c8e

View File

@ -18,6 +18,8 @@
#include <type_traits>
#include <limits>
#include <cstring>
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 <typename DstT, typename SrcT>
DstT
bit (SrcT &&src)
{
static_assert (sizeof (DstT) == sizeof (SrcT));
static_assert (std::is_trivially_copyable_v<std::decay_t<DstT>>);
static_assert (std::is_trivially_copyable_v<std::decay_t<SrcT>>);
DstT dst;
std::memcpy (&dst, &src, sizeof (DstT));
return dst;
}
}