mirror of
https://github.com/bkaradzic/bx.git
synced 2026-02-17 20:52:37 +01:00
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:
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user