开发者

Possible to Use typeid to Determine Parent-Child Relationship

all the while, I am using dynamic_cast to determine Parent-Child relationship of an 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
    }

  开发者_如何学Go  C* c = dynamic_cast<C *>(&b);
    if (c) {
        std::cout<< "is child of C"<< std::endl;    // Not printed
    }
    getchar();
}

May I know is it possible that I can determine parent-child relationship, of an object, through typeid? For example, how I can know B is the child of A, by using typeid checking?

Thanks.


I don't think you can do that in current C++ using the information in typeinfo only. I know of 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";
}


typeid is opaque. It is not meant to be a form of reflection. That said, doing a null check on the return from dynamic_cast is probably just as fast trying to traverse typeid structures to determine class relationships. Stick with dynamic_cast in pre-C++0x code.


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

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜