struct / cast / ? design problem

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 16 13:24:30 PDT 2015


The problem in your example is that your making a copy of the 
returned data. Of course any changes to that copy won't affect 
the original. You need to return a pointer to it (`ref` won't do 
if you want to store it in a local variable, because these can't 
be `ref`).

struct BlockHead
{
     uint magic = 20150312;
     uint magic2;
     uint blockSize;
     uint unused1;
     ulong unused2;
     ulong spare[61];

     T* embedded(T)() {
         static assert(T.sizeof < spare.length);
         return cast(T*) spare.ptr;
     }
}

How to use it:

void useIt(ref BlockHead bh) {
     static struct InternalData {
         int foo;
         ubyte[20] bar;
     }

     auto data = bh.embedded!InternalData;
     data.foo = 42;
}


More information about the Digitalmars-d-learn mailing list