Skip to content

Instantly share code, notes, and snippets.

@remyroez
Created November 14, 2016 09:04
Show Gist options
  • Save remyroez/215f3d321abb175a8260f1cd39fb346b to your computer and use it in GitHub Desktop.
Save remyroez/215f3d321abb175a8260f1cd39fb346b to your computer and use it in GitHub Desktop.
Force cast
#include <iostream>
template <typename T, typename U>
constexpr inline T &force_cast(U &u) { return (*reinterpret_cast<T *>(&u)); }
template <typename T, typename U>
constexpr inline const T &force_cast(const U &u) { return (*reinterpret_cast<const T *>(&u)); }
struct foo { int value = 123; };
int main()
{
auto a = 1.23f;
auto b = force_cast<int>(a);
auto c = force_cast<decltype(a)>(b);
auto d = force_cast<foo>(456);
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
std::cout << d.value << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment