fork(15) download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. template<class ID,class Base,class ... Args> class GenericObjectFactory{
  6. private:
  7. typedef Base* (*fInstantiator)(Args ...);
  8. template<class Derived> static Base* instantiator(Args ... args){
  9. return new Derived(args ...);
  10. }
  11. std::map<ID,fInstantiator> classes;
  12.  
  13. public:
  14. GenericObjectFactory(){}
  15. template<class Derived> void add(ID id){
  16. classes[id]=&instantiator<Derived>;
  17. }
  18. fInstantiator get(ID id){
  19. return classes[id];
  20. }
  21.  
  22. };
  23.  
  24. using namespace std;
  25.  
  26. class Animal{
  27. public:
  28. Animal(bool isAlive,string name) : isAlive(isAlive),name(name){};
  29. bool isAlive;
  30. string name;
  31. virtual string voice() const=0;
  32. };
  33. class Dog : public Animal{
  34. public:
  35. using Animal::Animal;
  36. string voice() const{
  37. return this->isAlive?
  38. "Woof! I'm "+this->name+"\n":
  39. "";
  40. }
  41. };
  42. class Cat : public Animal{
  43. public:
  44. using Animal::Animal;
  45. string voice() const{
  46. return this->isAlive?
  47. "Meow, I'm "+this->name+"\n":
  48. "";
  49. }
  50. };
  51.  
  52. int main(void){
  53. GenericObjectFactory<string,Animal,bool,string> animalFactory;
  54.  
  55. animalFactory.add<Dog>("man's friend");
  56. animalFactory.add<Cat>("^_^");
  57.  
  58. Animal *dog1=animalFactory.get("man's friend")(true,"charlie");
  59. Animal *dog2=animalFactory.get("man's friend")(false,"fido");
  60. Animal *cat =animalFactory.get("^_^")(true,"begemoth");
  61.  
  62. cout << dog1->voice()
  63. << dog2->voice()
  64. << cat ->voice();
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Woof! I'm charlie
Meow, I'm begemoth