novelrt / NovelRT

A cross-platform 2D game engine accompanied by a strong toolset for visual novels.
MIT License
183 stars 43 forks source link

Replace reinterpret_cast with `NovelRT::Utilities::Misc::BitCast` where appropriate #543

Open Pheubel opened 1 year ago

Pheubel commented 1 year ago

With the addition of NovelRT::Utilities::Misc::BitCast type punning can be expressed in a more easy to understand way. It has been used in a few places so far, but might be able to be used in more places to better express what is going on.

Something to watch out for is that when bitcasting an instance through pointers, such as this, you should take care and see if you should de-reference a variable before passing it as an argument. As some types have the same size as pointers, you might end up transforming the pointer instead of it's value.

Example

Taking the following example:

inline bool operator==(GeoVector2F other) const noexcept
{
    return *reinterpret_cast<const glm::vec2*>(this) == *reinterpret_cast<const glm::vec2*>(&other);
}

Would become:

inline bool operator==(GeoVector2F other) const noexcept
{
    return NovelRT::Utilities::Misc::BitCast<glm::vec2>(*this) == NovelRT::Utilities::Misc::BitCast<glm::vec2>(other);
}