Bit Cast

Header aarith/core/bit_cast.hpp

Unfortunately, there is no easy way to completely re-interpret bits as a different type. There is the usual trick of using an union. This is undefined behavior. This is why we opted to use the solution from this talk.

In the near future, when C++20 is more widely availabe, we will switch to using std::bit_cast

namespace aarith

Functions

template<typename To, typename From, typename = std::enable_if_t<(sizeof(To) == sizeof(From)) && std::is_trivially_copyable_v<From> && std::is_trivially_copyable_v<To>>>
To bit_cast(const From &src) noexcept

To avoid undefined behaviour when type punning, we are using memcpy. This is rather annoying but seems to be the way to go. The implementation is stolen from this talk: https://www.youtube.com/watch?v=_qzMpk-22cc

Todo:

replace with std::bit_cast when switching to C++20

Template Parameters
  • To – The type to convert to

  • From – The type to convert from

Parameters

src – The source of the bits

Returns

The new type filled with the bits of src