diff --git a/include/mav/utils.h b/include/mav/utils.h index 65736c1..f18a39e 100644 --- a/include/mav/utils.h +++ b/include/mav/utils.h @@ -203,25 +203,25 @@ namespace mav { } - template - A _packUnpack(B b) { - union U { - A a; - B b; - }; - U u; - u.b = b; - return u.a; + template + To _packUnpack(From o) { + static_assert(sizeof(To) == sizeof(From), "Cannot pack/unpack different sizes"); + static_assert(std::is_trivially_copyable::value, "Cannot pack/unpack non-trivially copyable types"); + static_assert(std::is_trivially_copyable::value, "Cannot pack/unpack non-trivially copyable types"); + To result; + std::memcpy(&result, &o, sizeof(To)); + return result; } + - template - T floatUnpack(float f) { - return _packUnpack(f); + template + To floatUnpack(float f) { + return _packUnpack(f); } - template - float floatPack(T o) { - return _packUnpack(o); + template + float floatPack(From o) { + return _packUnpack(o); }