Add bx::bit_cast method (#316)

This function provides the bx equivalent of std::bit_cast, in that it obtains
a value of type To by reinterpreting the object representation of From using
the memcpy aliasing method.
This commit is contained in:
pheonix
2024-01-28 19:40:33 -08:00
committed by GitHub
parent 67dfdf34f6
commit e5d5d0b7c6
2 changed files with 14 additions and 0 deletions

View File

@@ -214,6 +214,10 @@ namespace bx
template<typename Ty>
constexpr bool isPowerOf2(Ty _a);
/// Returns a value of type To by reinterpreting the object representation of From.
template <typename To, typename From>
constexpr To bit_cast(const From& value) noexcept;
/// Copy memory block.
///
/// @param _dst Destination pointer.

View File

@@ -147,4 +147,14 @@ namespace bx
return _a && !(_a & (_a - 1) );
}
template <typename To, typename From>
inline constexpr To bit_cast(const From& value) noexcept
{
BX_STATIC_ASSERT(sizeof(To) == sizeof(From), "To and From must be the same size.");
BX_STATIC_ASSERT(isTriviallyConstructible<To>(), "Destination target must be trivially constructible.");
To result;
bx::memCopy(&result, &value, sizeof(To));
return result;
}
} // namespace bx