fork download
  1. #include <iostream>
  2.  
  3. // Base class for entities
  4. class entity
  5. {
  6. public:
  7. virtual void do_walk() { std::cout << "I like walking" << std::endl; };
  8. };
  9.  
  10. // A class property for healer characters
  11. class healer
  12. {
  13. public:
  14. // interface
  15. virtual void do_heal() = 0;
  16. };
  17.  
  18. // A class property for healer npcs
  19. class merchant
  20. {
  21. public:
  22. // interface
  23. virtual void do_sell() = 0;
  24. };
  25.  
  26. // implementation of the healer property
  27. class healer_implementation : public healer
  28. {
  29. public:
  30. virtual void do_heal() { std::cout << "I heal people" << std::endl; }
  31. };
  32.  
  33.  
  34.  
  35. // implementation of the healer property
  36. class merchant_implementation : public merchant
  37. {
  38. public:
  39. virtual void do_sell() { std::cout << "I sell things" << std::endl; }
  40. };
  41.  
  42. // To deduce the implementation of a property, we'll use the template property which will be specialized for each property and reference an implementation
  43. template<typename T>
  44. class property
  45. {};
  46.  
  47. template<>
  48. class property<merchant>
  49. {
  50. public: typedef merchant_implementation implementation;
  51. };
  52.  
  53. template<>
  54. class property<healer>
  55. {
  56. public: typedef healer_implementation implementation;
  57. };
  58.  
  59.  
  60. // This class is a class helper to deduce the right class type from a list of property for an entity
  61. template<class... Property>
  62. class factory
  63. {
  64. public:
  65. class custom : public property<Property>::implementation..., public entity {};
  66.  
  67. };
  68.  
  69. int main()
  70. {
  71. entity* bob = new factory<healer, merchant>::custom();
  72.  
  73. // bob will try to sell things
  74. merchant* m = dynamic_cast<merchant*>(bob);
  75. if (m)
  76. m->do_sell();
  77.  
  78. // bob will try to heal people
  79. healer* h = dynamic_cast<healer*>(bob);
  80. if (h)
  81. h->do_heal();
  82.  
  83. // and as an entity, bob can walk
  84. bob->do_walk();
  85.  
  86. entity* frank = new factory<healer>::custom();
  87.  
  88. // frank will try to sell things
  89. m = dynamic_cast<merchant*>(frank);
  90. if (m)
  91. m->do_sell();
  92.  
  93. // frank will try to heal people
  94. h = dynamic_cast<healer*>(frank);
  95. if (h)
  96. h->do_heal();
  97.  
  98. // and as an entity, frank can walk
  99. frank->do_walk();
  100. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
I sell things
I heal people
I like walking
I heal people
I like walking