What is the best way to make sure that a C++ class conforms my expectations on how its data members are laid out?
I need to work with a class from 3rd party library. I know that this class is standard_layout
and I know it contains certain public data members (to be specific, I am talking about a C struct here). However, I do not necessarily know in which order the members are laid out in the struct and I do not know if there are extra data members.
I need to be able to assert that the data members are laid out in a certain order and that there are no extra members because my objective is to put this struct in a union and use the special ruling from 9.2 about the common initial sequence of the union. Preferably, I would like this to be a static_assert
of some kind, but a check in the build system using a small test program would be acceptable as well.
I was thinking of using the ofssetof
macro to check the ordering of the members, but I am a bit at loss on how to make sure there are no additional members hidden in the padding.
EDIT
I suppose a way to rephrase the question is:
- can I detect the declaration order of a C struct (provided I know the names of its members),
- can I detect the presence of extra members in addition to the ones I know of?