I have a template class with a bool as its template parameter Dynamic<bool>
. Whether the parameter is true or false it has the exact same data members. they just differ in their member functions.
There is one situation that I need to convert one to another temporarily, instead of using a copy/move constructor. So I resorted to type-punning. To make sure that it cause an issue I used two static_asserts
:
d_true=Dynamic<true>(...);
...
static_assert(sizeof(Dynamic<true>)==sizeof(Dynamic<false>),"Dynamic size mismatch");
static_assert(alignof(Dynamic<true>)==alignof(Dynamic<false>),"Dynamic align mismatch");
Dynamic<false>& d_false=*reinterpret_cast<Dynamic<false>*>(&d_true);
...
So I think what I am doing is safe, and if anything is about to go wrong the compiler will give me a static_assert
error. However, gcc gives a warning:
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
My question is twofold: is what I am doing the best way to achieve this? If it is, how can convince gcc it is safe, and get rid of the warning?