fork(1) download
  1. #include <map>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class A
  6. {
  7. public:
  8. typedef A *creator();
  9. typedef map<int,creator*> creatormap;
  10. static creatormap &getmap()
  11. {
  12. static creatormap amap;
  13. return amap;
  14. }
  15. template<class T> static void reg(int value)
  16. {
  17. getmap()[value]=[] () -> A* { return new T(); };
  18. }
  19. static A *make(int value)
  20. {
  21. creator *fun=getmap()[value];
  22. return (fun?fun():0);
  23. }
  24. };
  25.  
  26. class B:public A
  27. {
  28. public:
  29. B() { cout<<"B"<<endl; }
  30. };
  31.  
  32. class C:public A
  33. {
  34. public:
  35. C() { cout<<"C"<<endl; }
  36. };
  37.  
  38. class D:public C
  39. {
  40. public:
  41. D() { cout<<"D"<<endl; }
  42. };
  43.  
  44. void reg()
  45. {
  46. A::reg<B>(1);
  47. A::reg<C>(2);
  48. A::reg<D>(3);
  49. }
  50.  
  51. int main()
  52. {
  53. reg();
  54. A *b=A::make(1);
  55. A *c=A::make(2);
  56. A *d=A::make(3);
  57. A *a=A::make(0);
  58. if(!a) cout<<"is NULL and it is OK"<<endl;
  59. delete b;
  60. delete c;
  61. delete d;
  62. return 0;
  63. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
B
C
C
D
is NULL and it is OK