I've got a base class with (potentially) a lot of subclasses, and I would like to be able to compare any two objects of the base class for equality. I am trying to do this without invoking the blasphemous typeid keyword.
#include <iostream>
struct Base {
virtual bool operator==(const Base& rhs) const
{return rhs.equalityBounce(this);}
virtual bool equalityBounce(const Base* lhs) const = 0;
virtual bool equalityCheck(const Base* lhs) const = 0;
};
struct A : public Base {
A(int eh) : a(eh) {}
int a;
virtual bool equalityBounce(const Base* lhs) const{
return lhs->equalityCheck(this);
}
virtual bool equalityCheck(const Base* rhs) const {return false;}
virtual bool equalityCheck(const A* rhs) const {return a == rhs->a;}
};
int main() {
Base *w = new A(1), *x = new A(2);
std::cout << (*w == *w) << "\n";
std::cout << (*w == *x) << "\n";
}
I understand that the code as written is failing because lhs in equalityBounce() is a Base*, so it doesn't even know about the version of equalityCheck() that takes an A*. But I don't know what to do about it.
Aucun commentaire:
Enregistrer un commentaire