检查哪个子类是父类对象

Check which child class is a parent class object

本文关键字:父类 对象 子类 检查      更新时间:2023-10-16

我们有一个方法,它被传递给一个类作为参数。此类具有不同的子类。我们需要知道这些类中的哪一个是作为参数传递给此方法的类。由于赋值要求,我们无法为每个可能的类定义一种方法。此外,如果此方法不支持子类,则必须在编译时引发错误。 我们一直在尝试使用 static_cast 来执行此操作,但我们没有获得所需的结果,因为两个子类之间的转换始终是可能的。

class A{
...
};
class B : public A{
...
};
class C : public A{
...
}
void foo(A a){
if(a is B){
//OK and do stuff
}else if(a is C){
//throw compile error
}
}

您可以将foo本身编写为模板,以便在编译时执行所有检查:

#include <type_traits>
template<class T>
void foo(T t)
{
static_assert(std::is_same<T, C>::value == false,
"foo() must not be invoked with object of class C");
if (std::is_same<T, B>::value) {
// do stuff
}
}

static_assert用于某些条件的编译时检查,std::is_same编译时比较两种类型。