Checking runtime object type
Jonathan M Davis
jmdavisProg at gmx.com
Wed Feb 8 11:41:51 PST 2012
On Wednesday, February 08, 2012 20:21:45 Johannes Pfau wrote:
> Am Wed, 8 Feb 2012 11:20:39 -0800
>
> schrieb "H. S. Teoh" <hsteoh at quickfur.ath.cx>:
> > What's the correct syntax for checking the runtime type of a derived
> >
> > object given its base class pointer? I tried:
> > Base f() { return new Derived(); }
> > Base b = f();
> > assert(is(typeof(b)==Derived));
> >
> > but it throws an error. Apparently typeof(b)==Base; so typeof returns
> > only compile-time information? How do I get at the runtime type?
> >
> >
> > T
>
> I think using casts is the only way:
>
> Base f() { return new Derived(); }
> Base b = f();
> auto c = cast(Derived)b;
> assert(c !is null);
Casting is definitely the way that you're supposed to do it. If the cast
results in null, then the class is _not_ of the type that you cast to. e.g.
if(auto d = cast(Derived) b)
//do stuff with d
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list