タイプAとタイプB、またはBとCなどの比較を気にしない場合は、クラスごとにオーバーロードされた等式演算子を実装するだけです。
class A {
public: int data;
bool operator==(const A& rhs) {
return (data == rhs.data);
}
};
class B : public A {
public: float more_data; bool something_else;
bool operator==(const B& rhs) {
return (A::operator==( data ) &&
more_data == rhs.more_data &&
something_else == rhs.something_else);
}
};
ただし、BまたはCから新しいクラスDを派生させると、問題が発生するため、これは危険です。
それ以外の場合は、実際に正しく実行するために、多くのdynamic_cast<>-ingを使用していくつかのコンパレータを実装する必要があります。または、各オブジェクトのハッシュコードを作成し、それを活用する関数を実装することもできます。
class A {
public: int data;
virtual long getHashCode() const {
// compute something here for object type A
}
// virtual here just in case you need to overload it in B or C
virtual bool equals( const A& obj ) const {
return (typeid(*this) == typeid(obj) &&
getHashCode() == obj->getHashCode());
}
};
class B : public A {
public: float more_data; bool something_else;
virtual long getHashCode() const {
// compute something here for object type B
}
};
class C : public A {
public: double more_data;
virtual long getHashCode() const {
// compute something here for object type C
}
};
オブジェクトの型を何らかの方法でハッシュコードに組み込む場合(上記には示されていません)、上記のばかげたtypeid()の比較を省くこともできます。