You can use typeid to determine the parent-child relationship

all the time, I use dynamic_cast to determine the parent-child relationship of the object.

#include <iostream> class A { public: virtual ~A() {} }; class B : public A { }; class C : public A { }; int main() { B b; std::cout<< typeid(b).name()<< std::endl; // class B A* a = dynamic_cast<A *>(&b); if (a) { std::cout<< "is child of A"<< std::endl; // printed } C* c = dynamic_cast<C *>(&b); if (c) { std::cout<< "is child of C"<< std::endl; // Not printed } getchar(); } 

Can I find out if it is possible that I can determine the parent-child relationship of an object via typeid? For example, how can I know that B is a child of A using type checking?

Thanks.

+3
source share
3 answers

I do not think that you can do this in current C ++ using information only in typeinfo . I know boost::is_base_of (Type Traits will be part of C ++ 0x):

 if ( boost::is_base_of<A, B>::value ) // true { std::cout << "A is a base of B"; } 
+4
source

typeid opaque. It should not be a form of reflection. However, performing a null return check from dynamic_cast is probably just as quickly trying to traverse typeid structures to determine class relationships. Stick to dynamic_cast in pre-C ++ 0x code.

0
source

You could just do something similar to the C ++ typeid example and get something like this: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com. ibm.xlcpp8a.doc / language / ref / the_typeid_operator.htm

:)

-1
source

All Articles