fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <memory>
  4. #include <string>
  5.  
  6. class Base {
  7. public:
  8. virtual void bar() const = 0;
  9. };
  10.  
  11. template <typename T>
  12. class Foo_template : public Base {
  13. T t;
  14. public:
  15. Foo_template(const T& tt) : t(tt) { }
  16. void bar() const override {
  17. std::cout << t << '\n';
  18. }
  19. };
  20.  
  21. class Foo_list {
  22. std::list<std::unique_ptr<Base>> list;
  23.  
  24. public:
  25. template <typename T>
  26. void add_to_list(T&& data) {
  27. auto ptr = std::make_unique<Foo_template<T>>(std::forward<T>(data));
  28. list.push_back(std::move(ptr));
  29. }
  30.  
  31. void bar_all() {
  32. for(auto& elem : list) elem->bar();
  33. }
  34. };
  35.  
  36. int main() {
  37. Foo_list list;
  38. list.add_to_list(2);
  39. list.add_to_list(std::string{ "Hello, World!" });
  40. list.bar_all();
  41. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
2
Hello, World!