Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of variable

If I understand correctly, typeid can determine the actual type in polymorphism, while typeof cannot.

Is it also true that their returns are used for different purposes: the return of typeof is used as type keyword that can define variable, but the return of typeid cannot?

Is there any way to both get the actual type for polymorphism and use the return as type keyword to define another variable? I hope to get the derived class type from a pointer pointing to the base class and define a variable of or a pointer to the derived class. Something like:

baseclass *p = new derivedclass  
typexxx(*p) *pp = dynamic_cast<typexxx(*p) *> (p); 
// would like to convert the pointer from pointing to a base class 
// to its derived class

Thank you very much!

like image 488
Tim Avatar asked Dec 31 '09 22:12

Tim


1 Answers

c++0x will have decltype which can be used like this:

int someInt;
decltype(someInt) otherIntegerVariable = 5;

but for plain old c++, unfortunately, no.

I suppose that decltype won't really be much help either though since you want the polymorphic type, not the declared type. The most straight forward way to do what you want is to attempt to dynamic cast to a particular type and check for NULL.

struct A {
    virtual ~A() {}
};
struct B : public A {};
struct C : public A {};

int main() {
    A* x = new C;
    if(B* b_ptr = dynamic_cast<B*>(x)) {
        // it's a B
    } else if(C* c_ptr = dynamic_cast<C*>(x)) {
        // it's a C
    }
}
like image 198
Evan Teran Avatar answered Oct 12 '22 23:10

Evan Teran