如何在运行时检查对象是否来自特定的类?

时间:2023-01-08 23:37:13

I want to handle all of the children of specific class the same way.

我希望以相同的方式处理特定类的所有子类。

So far I have been checking with dynamic_cast like this:

到目前为止,我一直在用dynamic_cast这样检查:

if(dynamic_cast<ParentClass*>(child_object))
{
  // handle the object
}

In the case I do not really need to cast the child object to use it, is there a better way of doing this?

在我不需要强制转换子对象来使用它的情况下,有更好的方法吗?

My first attempt was:

我的第一次尝试是:

if(std::is_base_of<ParentClass, typeid(child_object)>::value)

which of course does not work as the is_base_of expects two class arguments and the typeid() returns the std::type_info.

当然,is_base_of不需要两个类参数,而typeid()返回std:::type_info。

So my question is, what is the proper way of doing this? Or is the dynamic_cast the right facility to use even if the casted object is not used?

我的问题是,什么是正确的方法?或者,dynamic_cast是正确的工具,即使该对象没有被使用?

Update

Here is the concrete example of what I am trying to achieve. I am iterating over all the QGraphicsItem objects that are in collision with my object of interest. I want to handle only one group of those objects and ignore the rest. That group of objects has a common parent. So again is using the dynamic_cast the way to go, or are there better alternatives?

这是我正在努力实现的具体例子。我正在遍历与感兴趣的对象发生冲突的所有QGraphicsItem对象。我只想处理其中的一组对象,而忽略其余的对象。那组对象有一个公共的父对象。所以,使用dynamic_cast是一种选择,还是有更好的选择?

    for(QGraphicsItem* i : collidingItems())
    {
        if(dynamic_cast<ParentClass*>(i))
        {
            // handle specific group of objects that 
            //are children of ParentClass
        }
    }

1 个解决方案

#1


5  

dynamic_cast is the way to go. It is the only way to detect if the object is part of the inheritance tree for a certain class, since typeid will only give you the actual name of the class.

dynamic_cast是一种方法。这是检测对象是否是某个类的继承树的一部分的唯一方法,因为typeid只会给出类的实际名称。

That being said, if something specific needs to be done on objects of a given class, it should be a virtual method. Using RTTI is bad form usually, but especially here.

也就是说,如果需要对给定类的对象执行特定的操作,那么它应该是一个虚拟方法。使用RTTI通常是不好的形式,尤其是在这里。

#1


5  

dynamic_cast is the way to go. It is the only way to detect if the object is part of the inheritance tree for a certain class, since typeid will only give you the actual name of the class.

dynamic_cast是一种方法。这是检测对象是否是某个类的继承树的一部分的唯一方法,因为typeid只会给出类的实际名称。

That being said, if something specific needs to be done on objects of a given class, it should be a virtual method. Using RTTI is bad form usually, but especially here.

也就是说,如果需要对给定类的对象执行特定的操作,那么它应该是一个虚拟方法。使用RTTI通常是不好的形式,尤其是在这里。