Undo struct slicing by type-punning

ponce via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 14 10:35:22 PDT 2014


Ok, solved it, I just use pointer casts and it seems to work when 
the struct is sliced.


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?



More information about the Digitalmars-d-learn mailing list