从基类指针比较模板化子类的属性
Comparing properties of templated child classes from base class pointers
我有一个派生自父类的类模板。我将孩子作为Parent*
存储在向量中。稍后,我可以使用 typeid
来确定两个对象是否为同一类型。我想做的是比较两个相同类型的对象的属性。为简单起见,我省略了将对象存储在向量中,但概念演示如下:
#include <iostream>
#include <typeinfo>
#include <vector>
class Parent{ public: virtual ~Parent(){}};
template<typename T>
class TypedChild : public Parent
{
public:
virtual ~TypedChild(){}
T getValue() {return mValue;}
private:
T mValue;
};
int main()
{
Parent* child1 = new TypedChild<int>();
Parent* child2 = new TypedChild<float>();
std::vector<Parent*> objects;
objects.push_back(child1);
objects.push_back(child2);
if(typeid(*(objects[0])) == typeid(*(objects[1])))
if(objects[0]->getValue() == objects[1]->getValue()) // compiler error: Parent has no member named getValue
std::cout << "Success";
return 0;
}
当然,在这个例子中,我可以dynamic_cast在调用getValue()
之前TypedChild<int>
,但是在对象在向量中的真实情况下,我不知道它们的类型,我只知道它们是相同的类型,因此它们的getValue()
函数应该返回相同的类型,因此可以进行比较。
有什么方法可以进行比较吗?
在您的用例中,即使不是不可能,也很难避免dynamic_cast
。如果只想获取一个对象的值,则需要使用 dynamic_cast
,例如:
Parent* child = ...;
auto typedChild = dynamic_cast<TypedChild*>(child):
if ( typedChild )
{
int val = typedChild->getValue();
}
如果要比较两个对象的相等性,最好的情况是具有virtual
operator==()
函数。
class Parent
{
public:
virtual ~Parent(){}
virtual bool operator==(Parent const& rhs) const = 0;
};
template<typename T>
class TypedChild : public Parent
{
public:
virtual ~TypedChild(){}
T getValue() {return mValue;}
virtual bool operator==(Parent const& rhs) const
{
auto derivedRHS = dynamic_cast<TypedChild<T> const*>(&rhs);
if ( !derivedRHS )
{
return false;
}
return (this->mValue == derivedRHS->mValue);
}
private:
T mValue;
};
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 我的子类的属性是延迟初始化的
- 子类中具有不同值的静态基类属性
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- C++引用基类中的子类指针属性
- 在C++中,继承超类的正确方法是什么,以便它们的子类在超级类和子类中没有重复的属性?
- 在构造子类对象的过程中,更改一个类属性的数据类型会导致segfault
- 如果我希望子类向父类添加功能,我是否应该保护我的属性
- 从父类访问子类属性
- 从基类指针比较模板化子类的属性
- 在子类中定义一个属性,然后在父类中使用它,这在PHP中是一种奇怪的行为
- 如果某些实例不使用基类的属性,我应该继承子类吗?
- 访问子类的属性/函数
- 如何从实体组件系统的子类中访问属性