Check if the Type of an Object is inherited from a

2020-08-21 03:57发布

In C++, how can I check if the type of an object is inherited from a specific class?

class Form { };
class Moveable : public Form { };
class Animatable : public Form { };

class Character : public Moveable, public Animatable { };
Character John;

if(John is moveable)
// ...

In my implementation the if query is executed over all elements of a Form list. All objects which type is inherited from Moveable can move and need processing for that which other objects don't need.

3条回答
不美不萌又怎样
2楼-- · 2020-08-21 04:20

You are using private inheritance, so it is not possible to use dynamic_cast to determine whether one class is derived from another. However, you can use std::is_base_of, which will tell you this at compile time:

#include <type_traits>

class Foo {};

class Bar : Foo {};

class Baz {};

int main() 
{
    std::cout << std::boolalpha;
    std::cout << std::is_base_of<Foo, Bar>::value << '\n'; // true
    std::cout << std::is_base_of<Bar,Foo>::value << '\n';  // false
    std::cout << std::is_base_of<Bar,Baz>::value << '\n';  // false
}
查看更多
神经病院院长
3楼-- · 2020-08-21 04:23

What you need is dynamic_cast. In its pointer form, it will return a null pointer if the cast cannot be performed:

if( Moveable* moveable_john = dynamic_cast< Moveable* >( &John ) )
{
    // do something with moveable_john
}
查看更多
Emotional °昔
4楼-- · 2020-08-21 04:43

Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves.

Example:

//moveable will be non-NULL only if dyanmic_cast succeeds
Moveable* moveable = dynamic_cast<Moveable*>(&John); 
if(moveable) //Type of the object is Moveable
{
}
查看更多
登录 后发表回答