Initialization of unions

bearophile bearophileHUGS at lycos.com
Thu Sep 23 05:14:29 PDT 2010


Justin Johansson:

> One of the problems with C++ is that it is not possible
> to create unions with non-primitive members (e.g. structs)
> that have constructors.

Do you mean something like this?

struct S1 {
    int y;
    this(int x) { y = x; }
}

struct S2 {
    string t;
    this(string s) { t = s; }
}

union U {
    S1 s1;
    S2 s2;
}

static U u2 = { s2:S2("hello") };

void main() {
    U u = U(S1(10));
    assert(u.s1.y == 10);
    u.s2 = S2("hello");
    assert(u.s2.t == "hello");
    // U u3 = U(S2("hello")); // not possible
}


Bye,
bearophile


More information about the Digitalmars-d mailing list