fork download
  1. #include <cstdio>
  2.  
  3. // External implementation 1
  4. class SomeShape {};
  5. class SomeBody { public: SomeShape *shape; };
  6.  
  7. // External implementation 2
  8. class OtherShape {};
  9. class OtherBody { public: OtherShape *shape; };
  10.  
  11. //////////////
  12.  
  13. class Shape
  14. {
  15. public:
  16. virtual const char *name() { return "Shape"; }
  17. };
  18.  
  19.  
  20. template<class Shape>
  21. class Body
  22. {
  23. Shape *shape;
  24. public:
  25. void setShape(Shape *s) {
  26. shape=s;
  27. printf("Setting shape: %s\n", s->name());
  28. }
  29. };
  30.  
  31. template <class Shape, class Body>
  32. class Factory
  33. {
  34. public:
  35. Shape *makeShape()
  36. { return new Shape(); }
  37. Body *makeBody()
  38. { return new Body(); }
  39. };
  40.  
  41. //////////////
  42.  
  43. class AShape : public Shape
  44. {
  45. public:
  46. SomeShape *someShape;
  47. virtual const char *name() { return "AShape"; }
  48. };
  49.  
  50. class ABody : public Body<AShape>
  51. {
  52. protected:
  53. SomeBody *someBody;
  54. public:
  55. ABody() { someBody = new SomeBody; }
  56. };
  57.  
  58.  
  59. //////////////
  60.  
  61. class BShape : public Shape
  62. {
  63. public:
  64. OtherShape *otherShape;
  65. virtual const char *name() { return "BShape"; }
  66. };
  67.  
  68. class BBody : public Body<BShape>
  69. {
  70. protected:
  71. OtherBody *otherBody;
  72. public:
  73. BBody() { otherBody = new OtherBody; }
  74. };
  75.  
  76. using BFactory = Factory<BShape, BBody>;
  77. using AFactory = Factory<AShape, ABody>;
  78.  
  79. int main()
  80. {
  81. // Of course in a real program we would return
  82. // a particular Factory from some selection function,
  83. // this should ideally be the only place the user is
  84. // exposed to the implementation selection.
  85. AFactory f1;
  86. BFactory f2;
  87.  
  88. // Associate a shape and body in implementation 1
  89. auto *s1 = f1.makeShape();
  90. auto *b1 = f1.makeBody();
  91. b1->setShape(s1);
  92.  
  93. // Associate a shape and body in implementation 2
  94. auto *s2 = f2.makeShape();
  95. auto *b2 = f2.makeBody();
  96. b2->setShape(s2);
  97.  
  98. // This should not be possible, compiler error ideally
  99. //b2->setShape(s1);
  100.  
  101. return 0;
  102. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Setting shape: AShape
Setting shape: BShape