c++ - 验证基础对象是否属于特定的派生类型

标签 c++ rtti

我有一个 Visual Studio 2008 C++03 项目,我想在其中验证对象是否属于某种类型。

例如:

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

    A* b = new B();
    A* c = new C();

    assert( typeof( b ) == typeof( B ) );
    assert( typeof( b ) != typeof( C ) );

    assert( typeof( c ) == typeof( C ) );
    assert( typeof( c ) != typeof( B ) );

    assert( typeof( b ) != typeof( c ) );
    return 0;
}

有没有办法在 C++03 中做到这一点?怎么办?

最佳答案

您可以使用 dynamic_cast 尝试将其转换为基础/派生类型。如果它不返回 NULL,那么它是一个基类或派生自该类型(取决于您是向上还是向下转换层次结构)

关于c++ - 验证基础对象是否属于特定的派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10705655/

相关文章:

c++ - 当 int 不是 int (intX_t)

c++ - 这个 C++ 代码片段如何将任意类型转换为唯一整数?

c++ - dynamic_cast 向下转型 : How does the runtime check whether Base points to Derived?

go - Go 在运行时获取函数参数

delphi - 我可以将 Delphi TEdit(或类似的)简单地连接到类的已发布属性吗?

delphi - 如何获取TVirtualInterface的调用方法参数名称?

c++ - 使用 Mutex 的线程同步

c++ - 多态和继承打印

python - 如何从 python (py) 文件中调用 C++ 函数?

c++ - 功能覆盖在哪里完成?