检查哪个子类是父类对象
Check which child class is a parent class object
我们有一个方法,它被传递给一个类作为参数。此类具有不同的子类。我们需要知道这些类中的哪一个是作为参数传递给此方法的类。由于赋值要求,我们无法为每个可能的类定义一种方法。此外,如果此方法不支持子类,则必须在编译时引发错误。 我们一直在尝试使用 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
编译时比较两种类型。
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- C++ 将子类的对象添加到父类的向量中
- 对静态分配的子类对象进行静态分配的纯虚拟父类引用是否合法?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 使用父类实例化的向下转换对象
- 对象在称为指向父类的指针时会丢失其成员的数据
- 检查哪个子类是父类对象
- 将对象强制转换为派生类以访问父类的受保护成员
- 如何仅通过父类对象限制对象创建
- 当函数返回类型为父类时,如何返回子类的对象?
- 调用实际对象而不是父类的方法
- C++:使用父类运算符函数更新子类对象的继承变量
- 比较从父类继承但存储在父类的向量中的类的对象类型
- 强制转换为父类对象而不是引用时会出现哪些不良结果
- C++中包含父类对象的子类有什么问题(如果有的话)
- 用于容纳子对象的父类对象的动态数组
- 访问父类对象集合的成员的子类函数
- c++中父类对象的集合