C++中有没有一种惯用的方法来比较多态类型的对象等价性

Is there an idiomatic approach in C++ for comparing polymorphic types for object equivalence?

本文关键字:比较 方法 多态 对象 类型 有没有 一种 C++      更新时间:2023-10-16

我有指向多态类型的两个实例的Base*指针,我需要确定引用的对象是否等效。

我目前的方法是首先使用RTTI来检查类型是否相等。如果类型相等,那么我调用一个虚拟is_equivalent函数。

有更惯用的方法吗?

对于大多数派生类,等价仅仅意味着成员变量都具有相同的值

在C++中,这被称为"相等",通常使用operator==()来实现。在C++中,你可以覆盖运算符的含义,可以写:

MyType A;
MyType B;
if (A == B) {
    // do stuff
}

并让==调用您定义的自定义函数。

我想你想把相等和身份区分开来,身份意味着相同的对象(即相同的地址)。

您可以将其实现为成员函数或免费函数(来自维基百科):

bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);

在您的情况下,您希望为基类实现operator==,然后执行您正在执行的操作。

更具体地说,它看起来是这样的:

class MyBase
{
    virtual ~MyBase(); // reminder on virtual destructor for RTTI
    // ...
private:
    virtual bool is_equal(const MyBase& other);
    friend bool operator ==(const MyBase& a, const MyBase& b); 
    // ...    
};
bool operator ==(const MyBase& a, const MyBase& b)
{
    // RTTI check
    if (typeid(a) != typeid(b))
        return false;
    // Invoke is_equal on derived types
    return a.is_equal(b);
}

class D1 : MyBase
{
    virtual bool is_equal(const Base& other)
    {
        const D1& other_derived = dynamic_cast<const D1&>(other);
        // Now compare *this to other_derived
    }
};
class D2 : MyBase;
{ };

D1 d1; D2 d2;
bool equal = d1 == d2; // will call your operator and return false since
                       // RTTI will say the types are different