I'm working on a project that requires dynamic_cast. I understand its quite slow and should generally be avoided, that said I see no other way.
There is almost certainly another way. In my experience, 'unavoidable' use of dynamic_cast is due to design flaws elsewhere in the system.
In your usage, do you only need exact type matches, or do you need to take inheritance hierarchies into account?
Given the inheritance hierarchy:
C is a B B is a A
And the code:
C derived; A* basePtr = &derived; B* cast = dynamic_cast<B*>( basePtr );Using regular dynamic_cast (or a custom implementation that also takes inheritance hierarchies into account), then this cast will succeed, because the object is an A, a B and a C.
With a custom implementation based on exact matches only, then this cast would fail, because the object only identifies as a C -- the advantage of these kinds of RTTI systems is that they are a lot faster.
Well it's more like a bunch of strcmps in a loop. Worst case that I know of is a linear search of the target type in a list of all the legal class names of the dynamic type.
And this is why I ban dynamic_cast in my coding guidelines...
Imagine the language didn't have RTTI at all -- instead there was a free, cross-platform, but closed-source library that gave you easy RTTI. Despite it being closed source, people had stepped through the Asm to see how it worked, and found that on Windows it often resulted in a long loop of string comparisons.
How many users would that library have, compared to a simpler library, or compared to people just using their own extremely simple home-made RTTI systems based on enums, etc?
The only reason this horrible library does have any users at all, is because it's shipped with and integrated into the language. I believe in Keep-It-Simple-Stupid as a strong guideline, but in this case, keeping it simple for me would be to reinvent the wheel, to replace an over-complicated and bloated system with a simple one.