struct / cast / ? design problem
Charles Hixson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Mar 16 14:13:36 PDT 2015
On 03/16/2015 01:24 PM, via Digitalmars-d-learn wrote:
> 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;
> }
>
Nice! That looks like exactly what I was hoping for.
More information about the Digitalmars-d-learn
mailing list