Can you use RTTI to determine a union member?
Daniel Keep
daniel.keep.lists at gmail.com
Tue Oct 16 05:51:05 PDT 2007
Kirk McDonald wrote:
> Janice Caron wrote:
>> Suppose I have
>>
>> union U
>> {
>> A a;
>> B b;
>> C c;
>> }
>>
>> and a function f(U u)
>>
>> is there any way to determine at runtime, which union member has been
>> assigned? I guess I want to do something like
>>
>> void f(U u)
>> {
>> if (is(u.a.typeof == A)) /* stuff */
>> else if (is(u.a.typeof == B)) /* stuff */
>> else if (is(u.a.typeof == C)) /* stuff */
>> }
>>
>> except obviously that won't work because typeof is a compile time
>> thing, not a run time thing, and so it will always return A.
>>
>> I don't suppose there's a runtime solution? If not, I guess I'll just
>> do what I've been doing all along (that is, store the choice in an
>> enum outside the union).
>
> enum + union is the age-old solution to this. D doesn't store this
> information for you (which I think is a good thing).
>
Another solution is to use a variant datatype which will take care of
checking you're unboxing the right type.
-- Daniel
More information about the Digitalmars-d
mailing list