Can you use RTTI to determine a union member?
BCS
ao at pathlink.com
Tue Oct 16 08:04:29 PDT 2007
Reply to Janice,
> 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).
>
if A, B and C are classes then you can uses
(cast(A)(cast(Object)u.b) !is null)
(cast(B)(cast(Object)u.c) !is null)
(cast(C)(cast(Object)u.a) !is null)
note the twist of the types. this is to force DMD to actually do the cast.
It might work without it but might not.
More information about the Digitalmars-d
mailing list