Initialization of unions
Graham St Jack
Graham.StJack at internode.on.net
Sun Sep 26 23:45:15 PDT 2010
Hi Justin,
I am using a struct as a discriminated union in my version of the
concurrency framework, and it all seems to work just fine. Here is a
code fragment from the code that implements a simple protocol. The code
is generated by a template, so it is very easy to crank out a message
struct with lots of different kinds of payload.
struct jobMsg {
string name;
this(string name) {
this.name = name;
}
void read(InStream stream) {
name = stream.get!string;
}
void write(OutStream stream) {
stream(name);
}
}
struct Message {
uint kind;
union {
jobMsg job;
}
this(ref jobMsg msg) {
kind = 0;
job = msg;
}
this(InStream stream) {
kind = stream.get!uint;
switch(kind) {
case 0: job.read(stream); break;
default: assert(0, "Cannot read unsupported message kind");
}
}
void write(OutStream stream) {
stream(kind);
switch(kind) {
case 0: job.write(stream); break;
default: assert(0, "Cannot write unsupported message kind");
}
}
}
On 23/09/10 21:58, Justin Johansson wrote:
> On 23/09/2010 10:14 PM, bearophile wrote:
>> 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
>> }
>
> Yes, but not yes; something like that. You are obviously
> one step ahead of me so perhaps I should give up or else
> post the exact problem in C++. Still, it looks likes
> from what you have shown that D has some better union
> construction syntax than C++.
>
> I hope others can throw in their 2 cents.
>
> Bye,
> Justin
>
--
Graham St Jack
More information about the Digitalmars-d
mailing list