keywords: C++, instanceof, typeof

dynamic_cast

Java has keyword instanceof and C# has function typeof to check object type at run-time.

Does C++ have equivalent of instanceof?
Answer is dynamic_cast:

if(NewType* v = dynamic_cast<NewType*>(old))
{
    // old was safely casted to NewType
    v->doSomething();
}

dynamic_cast only works when compiler RTTI enabled.

dynamic_cast is an operation with big cost.

std::is_base_of

std::is_base_of

template<typename Base, typename T>
inline bool instanceof(const T*) {
    return std::is_base_of<Base, T>::value;
}

Usage:

if (instanceof<BaseClass>(ptr)) { ... }
Optimization for dynamic_cast

Priori - A Fast dynamic_cast<> Alternative
https://www.codeproject.com/Articles/609598/Priori-A-Fast-dynamic-cast-Alternative
https://github.com/DigitalInBlue/Priori

Fast dynamic cast in C++ for MSVC, outperforming the regular dynamic cast by up to 25 times
https://github.com/tobspr/FastDynamicCast

Cases

Eampple source:

class A
{
    int a;
};

class B
{
    char b;
};

int main(int argc, char* args[])
{
    A ca;
	
    A* Aptr = &ca;
    B* Bptr = dynamic_cast<B*>(Aptr);
	
    return 0;
}

Complication error:

error C2683:  'dynamic_cast': 'CA01' is not a polymorphic type

Caused by:
dynamic_cast is used to type checking which a class is polymorphic( own a virtual function in self or the class it derived from own a virtual function) or there’s an inheritance between two classes.

Solution 1:
Add virtual function in class which cast from;

class A
{
    int a;

    virtual void fun01() {}
};

Solution 2:
Source class(input parameter of dynamic_cast) inherit from target class.

class A
{
    int a;

};

class B : public A
{
    char b;
};

int main(int argc, char* args[])
{
    A ca;
    B cb;
	
    A* Aptr = &ca;
    B* Bptr = &cb;
    A* ptr = dynamic_cast<A*>(Bptr);
}

B* ptr = dynamic_cast<B*>(Aptr); was invalid if there’s no inheritance between A and B, there would be a compliation error.

Reference

C++ equivalent of instanceof
https://stackoverflow.com/questions/500493/c-equivalent-of-instanceof

Fast dynamic casting
http://www.stroustrup.com/fast_dynamic_casting.pdf

How slow is dynamic_cast?
http://www.nerdblog.com/2006/12/how-slow-is-dynamiccast.html


我与春风皆过客,你携秋水揽星河。----网络