www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - detect anonymous union at compile time

reply "cal" <callumenator gmail.com> writes:
Given:

struct S {
   union {
     int i;
     float f;
   }
}

is there any way to detect the fact that fields i and f will have 
the same offset from S? (Creating an instance of S and getting 
the relative addresses only works if the union is public).
Mar 28 2013
parent reply "Andrej Mitrovic" <andrej.mitrovich gmail.com> writes:
On Thursday, 28 March 2013 at 20:02:18 UTC, cal wrote:
 is there any way to detect the fact that fields i and f will 
 have the same offset from S?
void main() { static if (S.init.i.offsetof == S.init.f.offsetof) pragma(msg, "Union"); }
 (Creating an instance of S and getting the relative addresses 
 only works if the union is public).
.offsetof will also require access rights to the fields.
Mar 28 2013
next sibling parent "cal" <callumenator gmail.com> writes:
On Thursday, 28 March 2013 at 20:18:45 UTC, Andrej Mitrovic wrote:
 .offsetof will also require access rights to the fields.
Yeh this is the problem. I can map data layout of complex aggregates, even if the members are private, but unions mess that up. Restricting to public fields is an option, but i'd like to be able to get it all.
Mar 28 2013
prev sibling parent reply "cal" <callumenator gmail.com> writes:
On Thursday, 28 March 2013 at 20:18:45 UTC, Andrej Mitrovic wrote:
 On Thursday, 28 March 2013 at 20:02:18 UTC, cal wrote:
 .offsetof will also require access rights to the fields.
Just realized that format.d is able to figure it out, since it regardless of protection. Thanks
Mar 28 2013
parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 3/28/13, cal <callumenator gmail.com> wrote:
 Just realized that format.d is able to figure it out, since it

 regardless of protection. Thanks
Ah, I didn't even know .tupleof would contain .offsetof. void main() { static if (S.tupleof[0].offsetof == S.tupleof[1].offsetof) pragma(msg, "Union"); }
Mar 28 2013