Is there a faster way to detect object type at runtime than using dynamic_cast?
c++, dynamic, polymorphism, visual-c++
Solution
I always look on the use of `dynamic_cast` as a code smell. You can replace it in all circumstances with polymorphic behaviour and improve your code quality. In your example I would do something like this:
class GenericClass
{
virtual void DoStuff()
{
// do interesting stuff here
}
};
class InterestingDerivedClass : public GenericClass
{
void DoStuff()
{
// do nothing
}
};
class CallbackImpl : public ICallback {
void DoStuff( GenericClass* param ) {
param->DoStuff();
}
}
In your case, you cannot modify the target classes, you are programming to a contract implied by the declaration of the `GenericClass` type. Therefore, there is unlikely to be anything that you can do that would be faster than `dynamic_cast` would be, since anything else would require modifying the client code.
Problem
I have a hierarchy of types - GenericClass and a number of derived classes, InterestingDerivedClass included, GenericClass is polymorphic. There's an interface ``` interface ICallback { virtual void DoStuff( GenericClass* ) = 0; }; ``` which I need to implement. Then I want to detect the case when GenericClass* pointer passed into ICallback::DoStuff() is really a pointer to InterestingDerivedClass: ``` class CallbackImpl : public ICallback { void DoStuff( GenericClass* param ) { if( dynamic_cast<InterestingDerivedClass*>( param ) != 0 ) { return; //nothing to do here } //do generic stuff } } ``` The GenericClass and the derived classes are out of my control, I only control the CallbackImpl. I timed the dynamic_cast statement - it takes about 1400 cycles which is acceptable for the moment, but looks like not very fast. I tried to read the disassembly of what is executed during dynamic_cast in the debugger and saw it takes a lot of instructions. Since I really don't need the pointer to the derived class is there a faster way of detecting object type at runtime using RTTI only? Maybe some implementation-specific method that only checks the "is a" relationship but doesn't retrieve the pointer?