cast: add an approximate implementation of std::bit_cast
This commit is contained in:
parent
6782b821b9
commit
98d8bd4c8e
22
cast.hpp
22
cast.hpp
@ -18,6 +18,8 @@
|
|||||||
#include <type_traits>
|
#include <type_traits>
|
||||||
#include <limits>
|
#include <limits>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
|
||||||
namespace cruft::cast {
|
namespace cruft::cast {
|
||||||
///////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////
|
||||||
@ -222,4 +224,24 @@ namespace cruft::cast {
|
|||||||
cruft::debug::sanity (dst);
|
cruft::debug::sanity (dst);
|
||||||
return 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user