Undo struct slicing by type-punning

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 14 11:43:35 PDT 2014


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.

 > On Monday, 14 July 2014 at 13:23:57 UTC, ponce wrote:
 >> Hi,
 >>
 >> I am porting C++ code that undo "Object Slicing" by casting
 >> const-references:
 >> http://en.wikipedia.org/wiki/Object_slicing
 >>
 >>
 >> My translation in D Code
 >> ----
 >>
 >> struct A
 >> {
 >>  // stuff
 >> }
 >>
 >> struct B
 >> {
 >>   A a;
 >>   alias a this;
 >>  // stuff
 >> }
 >>
 >> void myFunction(ref const(A) a)
 >> {
 >>     if (<a-is-actually-a-B>)
 >>     {
 >>         // here goes the converstion to a B reference
 >>         myFunction2(*cast(const(B)*)(&a)); // using pointer to do
 >> type-punning
 >>     }
 >> }
 >>
 >> ----
 >>
 >>
 >> To do this, I need to by guaranteed an object passed through ref
 >> const(A) is never, ever passed by value. Is it safe to assume?

It is guaranteed by the language spec that yes, myFunction() takes an A 
by reference. However, you can't know where that A is coming from; so, 
the safety of that cast is up to you. Consider:

void foo(A a)         // <-- Already sliced
{
     myFunction(a);    // <-- Will perform invalid cast
}

Ali



More information about the Digitalmars-d-learn mailing list