如何在运行时检查类型?

时间:2022-09-29 17:06:49

I tried to check a pointer to what type was passed as the argument as follows:

我试着检查指向哪个类型作为参数传递的指针,如下所示:

#include <iostream>
struct A{};
struct B:A{};
struct C:A{};
C *c = new C;
B *b = new B;
A *a = new A;
void foo (A *a)
{
    if(dynamic_cast<B*>(a))
    {
        std::cout << "Type is B*" << std::endl; 
    //cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct B*' (source type is not polymorphic)
    }

    if(dynamic_cast<C*>(a))
    {
        std::cout << "Type is C*" << std::endl; 
        //cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct C*' (source type is not polymorphic)
    }
}

But the doesn't even compile. Is it possible to do that? I mean, to determine what pointer to what type we passed as a function argument?

但是甚至没有编译。有可能吗?我的意思是,确定我们作为函数参数传递的类型的指针是什么?

1 个解决方案

#1


1  

You need to change A's definition by adding at least one virtual function. Simplest solution: add virtual destructor:

您需要通过添加至少一个虚拟函数来更改A的定义。最简单的解决方案:添加虚拟析构函数:

struct A
{
    virtual ~A() {}
};

Then:

然后:

int main()
{
    foo(b);
    foo(c);
    return 0;
}

Output:

输出:

Type is B*
Type is C*

Try it here: link.

在这里试试:链接。

Oh, and I know, that is only a sample code, but these globals created with new look terrible.

哦,我知道,这只是一个示例代码,但是这些全局变形看起来很糟糕。

#1


1  

You need to change A's definition by adding at least one virtual function. Simplest solution: add virtual destructor:

您需要通过添加至少一个虚拟函数来更改A的定义。最简单的解决方案:添加虚拟析构函数:

struct A
{
    virtual ~A() {}
};

Then:

然后:

int main()
{
    foo(b);
    foo(c);
    return 0;
}

Output:

输出:

Type is B*
Type is C*

Try it here: link.

在这里试试:链接。

Oh, and I know, that is only a sample code, but these globals created with new look terrible.

哦,我知道,这只是一个示例代码,但是这些全局变形看起来很糟糕。