- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
template <class ToPtr,class From>
ToPtr DynamicCast (From f)
{
// static check if *ToPtr is derived from f
(void)sizeof (static_cast<From> ((ToPtr)NULL));
// lazy precalculation
static bool castable = dynamic_cast<ToPtr> (f)!=NULL;
static int offset =
int ((char *)dynamic_cast<ToPtr> (f)-(char *)f);
return castable? (ToPtr)((char *)f+offset) : NULL;
}
// usage: TBase *ptr1 = ...; TDerived *ptr2 = DynamicCast<TDerived *> (ptr1);
Follow us!