c++ - 通过检测当前 'this' 对象类型在 C++ 中进行类型转换

标签 c++ rtti

我的问题与 C++ 中的 RTTI 有关,我试图检查一个对象是否属于另一个对象的类型层次结构。 BelongsTo() 方法会检查这一点。 我尝试使用 typeid,但它会引发错误,并且我不确定是否有其他方法可以找到要在运行时转换的目标类型。

#include <iostream>
#include <typeinfo>

class X
{
    public:
        //  Checks if the input type belongs to the type heirarchy of input object type
        bool BelongsTo(X* p_a)
        {
            //  I'm trying to check if the current (this) type belongs to the same type 
            //  hierarchy as the input type
            return dynamic_cast<typeid(*p_a)*>(this) != NULL;   //  error C2059: syntax error 'typeid'
        }
};

class A : public X
{
};

class B : public A
{
};

class C : public A
{
};

int main()
{
    X* a = new A();
    X* b = new B();
    X* c = new C();
    bool test1 = b->BelongsTo(a);   // should return true
    bool test2 = b->BelongsTo(c);   // should return false
    bool test3 = c->BelongsTo(a);   // should return true
}

将方法设为虚拟并让派生类执行这似乎是一个坏主意,因为我在同一类型层次结构中有很多类。 或者有人知道任何其他/更好的方法来做同样的事情吗?请提出建议。

更新:b.BelongsTo(a) 应检测输入对象类型 (a) 是否是类型层次结构中当前对象 (b) 的祖先。

最佳答案

这没有意义 - 您可以调用该函数这一事实意味着该参数属于 X 层次结构,因为这是参数的类型。动态转换旨在找出已知层次结构中的实际类型。

代码中的语法错误:

return dynamic_cast<typeid(*p_a)*>(this) != NULL;  

是因为 typeid 不是类型 - 你根本不能将它用作像这样的dynamic_cast类型。

如果按照 Naveen 的建议,您想查明某个实例是否属于子层次结构,请使用:

if ( dynamic_cast <A*>( some_x_ptr ) ) {

    // yes, belongs to A sub-hierarchy
}

编辑:您有:

A <- P <- X
A <- Q <- Y

然后:

A * a = new X;

dynamic_cast <P *>( a );   // not null
dynamic_cast <Q *>( a );   // null

关于c++ - 通过检测当前 'this' 对象类型在 C++ 中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956404/

相关文章:

c++ - 用双链表实现的堆栈的一个错误

c++ - 在编译时使用 gnu++11 过滤值列表,不使用 stdlib(Arduino 环境)

C++ map : manipulate map inside map

Delphi - 使用 RTTI e Addr 获取相同的字段指针

Delphi 类帮助器 RTTI GetMethod

德尔福: How to create a generic type programatically?

delphi - 为什么枚举类型会出现 "type has no typeinfo"错误

c++ - 使用具有部分类特化的 CRTP?

c++ - 提升 lambda 困惑

delphi - 获取特定属性的属性值