fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3. using namespace std;
  4.  
  5. struct A {
  6. virtual bool operator==(const A &other) const = 0;
  7. };
  8.  
  9. template<typename Base, typename Derived>
  10. struct PolymorphicComparable : public Base {
  11. bool operator==(const Base &other) const {
  12. if (typeid(other) != typeid(Derived))
  13. return false;
  14. const Derived & a = static_cast<const Derived&>(*this);
  15. const Derived & b = static_cast<const Derived&>(other);
  16. return a == b; // call Derived::operator==(Derived)
  17. }
  18. };
  19.  
  20. struct A1 : public PolymorphicComparable<A,A1>
  21. {
  22. int i;
  23. A1(int i) : i(i) {}
  24.  
  25. bool operator==(const A1 &other) const {
  26. return i == other.i;
  27. }
  28. };
  29.  
  30. struct A2 : public PolymorphicComparable<A,A2>
  31. {
  32. float f;
  33. A2(float f) : f(f) {}
  34.  
  35. bool operator==(const A2 &other) const {
  36. return f == other.f;
  37. }
  38. };
  39.  
  40.  
  41. int main() {
  42. A * a = new A1(5);
  43. A * b = new A1(2);
  44. A * c = new A2(7.6);
  45. A * d = new A2(7.6);
  46.  
  47. // Comparing objects of same dynamic type:
  48. cout << (*a == *b) << endl;
  49. cout << (*c == *d) << endl;
  50.  
  51. // Comparing objects of different dynamic types:
  52. cout << (*a == *c) << endl;
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
0
1
0