fork download
  1. #include <iostream>
  2.  
  3. class IBase {
  4. public:
  5. virtual void report() const = 0;
  6. virtual IBase * instance() const = 0;
  7. };
  8.  
  9. template <typename Derived>
  10. class Builder : public IBase {
  11. public:
  12. IBase *instance() const {
  13. return new Derived;
  14. }
  15. };
  16.  
  17. class B : public Builder<B> {
  18. public:
  19. virtual void report() const {
  20. std::cout << "B" << std::endl;
  21. }
  22. };
  23.  
  24. class C : public Builder<C> {
  25. public:
  26. virtual void report() const {
  27. std::cout << "C" << std::endl;
  28. }
  29. };
  30.  
  31. int main() {
  32. IBase *b = new B;
  33. IBase *c = new C;
  34.  
  35. b->report();
  36. c->report();
  37.  
  38. IBase *b1 = b->instance();
  39. IBase *c1 = c->instance();
  40.  
  41. b1->report();
  42. c1->report();
  43. }
Success #stdin #stdout 0.02s 2812KB
stdin
Standard input is empty
stdout
B
C
B
C