rtti cast
Pragma
eric.t.anderton at gmail.com
Fri May 2 07:26:13 PDT 2008
terranium Wrote:
> Simon Buerger Wrote:
>
> > BCS wrote:
> > > this work?
> > >
> > > if (auto y = cast(A)x)
> > > y.function_A();
> > > else if(auto y = cast(B)x)
> > > y.function_B();
> > >
> >
> > Well, honestly I'm really impressed. Thats perfectly what I wanted.
> > Seems to be standard, but I didn't knew about it *lolz*. Okay, seems
> > to be solved then. Thanks.
>
> OMG invalid cast doesn't throw exception????
Nope. Invalid casts simply return null. If you absolutely need an exception, then you can just wrap the cast in a templated function:
class DynamicCastException : Exception{
public this(char[] reason){
super(reason);
}
}
T dyn_cast(T)(Object x){
T result = cast(T)x;
if(result is null) throw new DynamicCastException("Cannot cast to type " ~ T.stringof);
return result;
}
class A{}
class B:A{}
class C{}
void main(){
B x = new B();
C y = dyn_cast!(C)(x);
}
More information about the Digitalmars-d
mailing list