void initialization vs alignment holes

bearophile bearophileHUGS at lycos.com
Sun Mar 7 10:05:55 PST 2010


strtr:
> static if( S.sizeof == members.sizeof )
>  S s = void;
> else
>  S s;

You can use something like this :-)

import std.stdio: writeln;

int unusedBytesStruct(S)() if (is(S == struct)) {
    int totUsed;
    foreach (field; S.init.tupleof)
        totUsed += field.sizeof;
    return cast(int)S.sizeof - totUsed;
}

struct S1 {
    byte s;
    double d;
}

align(1) struct S2 {
    byte s;
    double d;
}

struct T {
    double d;
    int x;
    short s;
    ubyte u1, u2;
}

void main() {
    writeln(unusedBytesStruct!S1); // 7
    writeln(unusedBytesStruct!S2); // 0
    writeln(unusedBytesStruct!T);  // 0
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list