
fast run-time type idenitification
Quote:
>Hi
>I need to determine as quickly as possible if a object is part of a type
>hierarchy.
>Check out the class hiearchy below.
>Class hierarchy
>A -----E
>|
>|
>B------C
>|
>|
>D
>What would the following be the fastest way to determine this?
>D* p;
>// initialized somewhere in the program
>IsB(p); // return true;
>E* g;
>IsB(g); // return false;
>bool IsB(A* p) {
>try {
> B* p = dynamic_cast<B*>(p);
> return true;
>}catch(std::bad_cast &e) {
> return false;
>}
>}
Only the reference form of dynamic_cast can throw an exception, so you
can reduce that to:
bool IsB(A* p)
{
return dynamic_cast<B*>(p);
Quote:
}
BTW, there's a bug such that a failed reference-type dynamic_cast
throws the bad_cast defined by <typeinfo.h>, not std::bad_cast defined
by <typeinfo>.
Quote:
>or would something along the lines with typeid be the fastest.
That's hard to say, but I would guess dynamic_cast would be faster.
You'll have to profile to be sure.
--
Doug Harrison [VC++ MVP]
Eluent Software, LLC
http://www.eluent.com
Tools for Visual C++ and Windows