fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class Root
  6. {
  7. public:
  8. explicit Root(double bar) : Bar(bar) {}
  9.  
  10. // Base class must have a virtual destructor for deletion through
  11. // the base pointer to work properly
  12. virtual ~Root() {}
  13.  
  14. bool operator==(const Root& other) const
  15. {
  16. // Make sure the two types being compared are the same derived type
  17. return (typeid(*this) == typeid(other)) &&
  18. // Compare all state associated with the base class
  19. (Bar == other.Bar) &&
  20. // Dispatch comparison to the derived implementation to finish
  21. // the comparison
  22. isEqual(other);
  23. }
  24.  
  25. private:
  26. // Guaranteed to only be dispatched by operator== if 'other' is the
  27. // same type as '*this'
  28. virtual bool isEqual(const Root &other) const = 0;
  29.  
  30. double Bar;
  31. };
  32.  
  33. class BranchA : public Root
  34. {
  35. public:
  36. BranchA(double bar, double baz) : Root(bar), BazA(baz) {}
  37.  
  38. private:
  39. virtual bool isEqual(const Root& other) const override
  40. {
  41. // static_cast is safe since the Base class guarantees it won't
  42. // call this function unless 'other' and '*this' are the same type
  43. const BranchA& branch = static_cast<const BranchA&>(other);
  44. return (BazA == branch.BazA);
  45. }
  46.  
  47. double BazA;
  48. };
  49.  
  50. class BranchB : public Root
  51. {
  52. public:
  53. BranchB(double bar, int baz, bool foo) : Root(bar), BazB(baz), Foo(foo) {}
  54.  
  55. private:
  56. virtual bool isEqual(const Root& other) const override
  57. {
  58. // static_cast is safe since the Base class guarantees it won't
  59. // call this function unless 'other' and '*this' are the same type
  60. const BranchB& branch = static_cast<const BranchB&>(other);
  61. return (BazB == branch.BazB) && (Foo == branch.Foo);
  62. }
  63.  
  64. int BazB;
  65. bool Foo;
  66. };
  67.  
  68. void compare_loop(const Root &r, const std::vector<std::unique_ptr<Root>>& vec)
  69. {
  70. for (const auto& v : vec)
  71. {
  72. if (r == *v)
  73. {
  74. std::cout << "Equivalent\n";
  75. }
  76. else
  77. {
  78. std::cout << "Different\n";
  79. }
  80. }
  81. }
  82.  
  83. int main()
  84. {
  85. BranchA root(1.0, 2.0);
  86.  
  87. std::vector<std::unique_ptr<Root>> branches;
  88. branches.push_back(std::make_unique<BranchA>(root));
  89. branches.push_back(std::make_unique<BranchA>(1.0, 1.0));
  90. branches.push_back(std::make_unique<BranchB>(1.0, 2.0, true));
  91.  
  92. compare_loop(root, branches);
  93.  
  94. return 0;
  95. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Equivalent
Different
Different