在C ++中是否有一种惯用的方法来比较对象等价的多态类型? [英] Is there an idiomatic approach in C++ for comparing polymorphic types for object equivalence?
问题描述
我有一个Base *指向一个多态类型的两个实例,我需要确定引用的对象是否是等价的。
I have Base* pointers to two instances of a polymorphic type and I need to determine if the referenced objects are equivalent.
我目前的方法是首先使用RTTI以检查类型相等。如果类型相等,我然后调用一个虚拟的is_equivalent函数。
My current approach is to first use RTTI to check for type equality. If the types are equal, I then call a virtual is_equivalent function.
有一个更惯用的方法吗?
Is there a more idiomatic approach?
推荐答案
对于大多数派生类,等价简单意味着成员变量都具有相同的值
For most of the derived classes, equivalent simply means that the member variables all the same value
在C ++中,这称为等号,通常使用 operator == c $ c>。在C ++中,你可以覆盖操作符的含义,可以写成:
In C++ this is called 'equality' and is usually implemented using operator==()
. In C++ you can override the meaning of operators, it is possible to write:
MyType A;
MyType B;
if (A == B) {
// do stuff
}
$ b b
有 ==
调用你定义的自定义函数。
And have ==
call a custom function you define.
我想你想区分相等
您可以将其实现为成员函数或自由函数(来自wikipedia):
You can implement it as member function or free function (from wikipedia):
bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);
在你的case你想实现 operator == $ c $
In your case you want to implement operator==
for the base class, and then perform what you are doing.
更具体地,它将是这样:
More concretely it would look like this:
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
这篇关于在C ++中是否有一种惯用的方法来比较对象等价的多态类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!