Tuesday 10 September 2013

C++ fast dynamic type/subtype check

C++ fast dynamic type/subtype check

As the title suggests, I am looking for a fast way of runtime
typechecking. To illustrate my problem, imagine you have a class hierarchy
like the following:
Base
/ \
A D
/ \ / \
C B F E
\ /
G
My program holds all instances of any class in a single list as Base_ptr
because all these classes share common tasks. Now at some point some
derived classes will need to know about the existence of an instance of
another class. So far so good, I know about dynamic_cast and the
typeid()-operator, but both have some mayor drawbacks:
dynamic_cast consumes a lot of processing time if the types are
incompatible (e.g. try to cast instances of E to C)
typeid() does not work in "isTypeOrSubtype"-cases, e.g. you need all
instances of D or derived from D (so Es, Fs and Gs as well)
The ideal solution would be some kind of "isTypeOrSubtype"-test and only
casting, if this test returns successfully. I got an own approach with
some macro definitions and precalculated classname hashes, but it is very
ugly and hardly maintainable. So I am looking for a cleaner and faster way
of dynamic type and subtype checking that can check far more than
20million times per second.

No comments:

Post a Comment