Add helper wrappers similar to std::bit_cast which support size mismatches
This commit is contained in:
@@ -32,4 +32,28 @@ constexpr To bit_cast(const From& from) noexcept
|
||||
|
||||
#endif
|
||||
|
||||
template <typename To, typename From>
|
||||
constexpr To bit_cast_to_storage(const From& from) noexcept
|
||||
{
|
||||
static_assert(std::is_trivially_constructible_v<To>);
|
||||
static_assert(std::is_trivially_copyable_v<From>);
|
||||
static_assert(sizeof(To) >= sizeof(From));
|
||||
|
||||
To to{};
|
||||
memcpy(&to, &from, sizeof(From));
|
||||
return to;
|
||||
}
|
||||
|
||||
template <typename To, typename From>
|
||||
constexpr To bit_cast_from_storage(const From& from) noexcept
|
||||
{
|
||||
static_assert(std::is_trivially_constructible_v<To>);
|
||||
static_assert(std::is_trivially_copyable_v<From>);
|
||||
static_assert(sizeof(To) <= sizeof(From));
|
||||
|
||||
To to{};
|
||||
memcpy(&to, &from, sizeof(To));
|
||||
return to;
|
||||
}
|
||||
|
||||
#endif /* BIT_CAST_HPP */
|
||||
|
Reference in New Issue
Block a user