从基类指针比较模板化子类的属性

Comparing properties of templated child classes from base class pointers

本文关键字:子类 属性 基类 指针 比较      更新时间:2023-10-16

我有一个派生自父类的类模板。我将孩子作为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;
};