fork(7) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A
  5. {
  6. public:
  7. bool operator==(const A& a) const
  8. {
  9. return equals(a);
  10. }
  11. protected:
  12. virtual bool equals(const A& a) const = 0;
  13. };
  14.  
  15. template<class T>
  16. class A_ : public A
  17. {
  18. protected:
  19. virtual bool equals(const A& a) const
  20. {
  21. const T* other = dynamic_cast<const T*>(&a);
  22. return other != nullptr && static_cast<const T&>(*this) == *other;
  23. }
  24. private:
  25. bool operator==(const A_& a) const // force derived classes to implement their own operator==
  26. {
  27. return false;
  28. }
  29. };
  30.  
  31. class B : public A_<B>
  32. {
  33. public:
  34. B(int i) : id(i) {}
  35. bool operator==(const B& other) const
  36. {
  37. return id == other.id;
  38. }
  39. private:
  40. int id;
  41. };
  42.  
  43. class C : public A_<C>
  44. {
  45. public:
  46. C(int i) : identity(i) {}
  47. bool operator==(const C& other) const
  48. {
  49. return identity == other.identity;
  50. }
  51. private:
  52. int identity;
  53. };
  54.  
  55. const char * TF(bool b)
  56. {
  57. return b ? "True" : "False";
  58. }
  59.  
  60. int main() {
  61. B b1(1);
  62. B b2(2);
  63. C c1(1);
  64. C c2(1);
  65. A& a1 = b1;
  66. A& a2 = b2;
  67. A& a3 = c1;
  68. A& a4 = c2;
  69. cout << "a1 == b1: " << TF(a1 == b1) << endl;
  70. cout << "a1 == a2: " << TF(a1 == a2) << endl;
  71. cout << "a2 == a3: " << TF(a2 == a3) << endl;
  72. cout << "a3 == a4: " << TF(a3 == a4) << endl;
  73.  
  74. // your code goes here
  75. return 0;
  76. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
a1 == b1: True
a1 == a2: False
a2 == a3: False
a3 == a4: True