Undo struct slicing by type-punning
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jul 14 14:55:01 PDT 2014
On 07/14/2014 02:34 PM, ponce wrote:
> On Monday, 14 July 2014 at 18:43:36 UTC, Ali Çehreli wrote:
>> On 07/14/2014 10:35 AM, ponce wrote:
>>
>> > Ok, solved it, I just use pointer casts and it seems to work
>> when the
>> > struct is sliced.
>>
>> I think there is a terminology issue here. Slicing cannot be undone;
>> once the object is sliced, the non-A parts are gone.
>>
>
> Well they are not really gone if the struct is passed by-ref,
Oh, it's not slicing in that case... but wait! There is a problem here. :)
In C++, both structs and classes are value types and they both support
inheritance. To observe slicing in C++, one needs pass-by-value and
inheritance, which is available by structs and classes.
In D, structs don't support inheritance and classes don't support
pass-by-value. However... Enter 'alias this' and we have D's version of
slicing.
> you can recover the "gone" parts: http://dpaste.dzfl.pl/d64863fd4c6d
Aggreed but in D's case the non-A parts are not gone; as long as A
lives, we know that B is alive. This is different from C++ where due to
the necessary pass-by-value, they are truly gone (the bits may still be
there but a C++ code should not do as D does).
Ali
More information about the Digitalmars-d-learn
mailing list