fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <functional>
  4. #include <vector>
  5. #include <iterator>
  6.  
  7. class Base
  8. {
  9. public:
  10. static Base* build(std::istream& in)
  11. {
  12. int x;
  13. in >> x;
  14. return new Base(x);
  15. }
  16. Base(int x) {};
  17. virtual void whoAmI()
  18. {
  19. std::cout << "Base\n";
  20. }
  21. };
  22.  
  23. class Derived: public Base
  24. {
  25. public:
  26. static Derived* build(std::istream& in)
  27. {
  28. int x, y;
  29. in >> x >> y;
  30. return new Derived(x, y);
  31. }
  32. Derived(int x, int y) : Base(x) {};
  33. virtual void whoAmI() override
  34. {
  35. std::cout << "Derived\n";
  36. }
  37. };
  38.  
  39. template <class OutputIterator>
  40. OutputIterator loadData(std::istream& in, OutputIterator it)
  41. {
  42. using map_type = const std::unordered_map<int, std::function<Base*(std::istream&)>>;
  43. static map_type builders = { {1, Base::build}, {2, Derived::build}, };
  44. int x;
  45. while(in >> x)
  46. *it++ = builders.at(x)(in);
  47. return it;
  48. }
  49.  
  50.  
  51. int main()
  52. {
  53. std::vector<Base*> pointers;
  54. loadData(std::cin, std::back_inserter(pointers));
  55. for(auto p: pointers)
  56. p -> whoAmI();
  57. }
  58.  
Success #stdin #stdout 0s 3480KB
stdin
1 9000 
2 42 14 
1 1 
1 64
2 2 2
2 33 444
x
stdout
Base
Derived
Base
Base
Derived
Derived