New abstraction: Layout

Steven Schveighoffer schveiguy at yahoo.com
Sat Feb 17 14:03:03 UTC 2018


On 2/17/18 8:19 AM, Steven Schveighoffer wrote:
> On 2/16/18 7:04 PM, Andrei Alexandrescu wrote:
>> I've been long bothered that the builtin .tupleof and our own 
>> abstractions Fields and RepresentationTypeTuple in std.traits - all 
>> omit the essential information of field offsets. That makes types that 
>> use align() to have the same .tupleof, Fields, and 
>> RepresentationTypeTuple even though they shouldn't.
>>
>> The right answer is Layout a tuple of (offset, type) pairs describing 
>> entirely the memory layout of a type. We need such for memory 
>> allocation, garbage collection, serialization, and more.
>>
>> The implementation turned out to be quite compact - 81 lines including 
>> a compile-time mergesort. Destroy!
>>
>> https://github.com/dlang/phobos/pull/6192
> 
> Can't you just use offsetof?
> 
> struct S
> {
>     ubyte x;
>     int y;
> }
> 
> static foreach(i; 0 .. s.tupleof.length)
> {
>     writeln(s.tupleof[i].offsetof);
> }
> 
> outputs:
> 0
> 4

I found this also works:

static foreach(alias x; S.tupleof)
{
    writeln(x.offsetof);
}

-Steve


More information about the Digitalmars-d mailing list