Skip to content

Instantly share code, notes, and snippets.

@mbitsnbites
Last active July 16, 2018 13:40
Show Gist options
  • Save mbitsnbites/fdfea67c1ff35960c1e33f724119faa6 to your computer and use it in GitHub Desktop.
Save mbitsnbites/fdfea67c1ff35960c1e33f724119faa6 to your computer and use it in GitHub Desktop.
raw_cast<T>() - C++ type punning
#include <cstring>
template <typename T2, typename T1>
inline T2 raw_cast(const T1& x) {
static_assert(sizeof(T2) == sizeof(T1), "raw_cast type sizes must match");
T2 result;
std::memcpy(static_cast<void*>(&result), static_cast<const void*>(&x), sizeof(T2));
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment