Is there a way to implement offsetof for non-POD types without UB?

323 Views Asked by At

For a type T and it's member variable m, the simplest form of offsetof(T, m) would be

&static_cast<T*>(0)->m

although it is clearly UB. Is there a way to do the same thing without involving UB on the assumption that T is either POD or non-POD but there is no virtual inheritance? Or alternatively, is there a way to ensure at compile time that under the current implementation (by which the code is being compiled) the expression is guaranteed to be evaluated to the correct value?

For now I'm using the above expression without any issues in the current versions of GCC, Clang and Visual C++, but it is being threatened by GCC's Undefined Behavior Sanitizer which has been enforced recently in our codebase.

0

There are 0 best solutions below