fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4. #include <vector>
  5. using namespace std;
  6.  
  7. class Animal {
  8. public:
  9. virtual ~Animal() {}
  10. virtual void PrintName() = 0;
  11. protected:
  12. string mName;
  13. };
  14.  
  15. class Cat : public Animal {
  16. public:
  17. Cat(const string& inName)
  18. {
  19. mName = inName;
  20. }
  21. void PrintName() final {
  22. cout << "this is a " << mName << endl;
  23. }
  24. };
  25.  
  26. class Dog : public Animal {
  27. public:
  28. Dog(const string& inName)
  29. {
  30. mName = inName;
  31. }
  32. void PrintName() final {
  33. cout << "this is a " << mName << endl;
  34. }
  35. };
  36.  
  37. vector<unique_ptr<Animal>> MyAnimal;
  38.  
  39. template <class tDerived, class...tConstructArgs>
  40. tDerived* AddAnimal(tConstructArgs&&... inArgs)
  41. {
  42. auto theanimal = make_unique<tDerived>(forward<tConstructArgs>(inArgs)...);
  43. auto result = theanimal.get();
  44. MyAnimal.push_back(move(theanimal));
  45. return result;
  46. };
  47.  
  48. int main() {
  49. // your code goes here
  50. auto thepet = AddAnimal<Cat>("my cat");
  51. thepet->PrintName();
  52. for(const auto& pet:MyAnimal)
  53. {
  54. pet->PrintName();
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 5536KB
stdin
Standard input is empty
stdout
this is a my cat
this is a my cat