fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <memory>
  5. using namespace std;
  6.  
  7. struct parent_class {
  8. virtual void say_hello() { cout << "Hello, I'm parent"<<endl; }
  9. virtual ~parent_class() {}
  10. };
  11. struct child_class : parent_class {
  12. void say_hello() override { cout << "Hello, I'm child"<<endl; }
  13. };
  14.  
  15. template <typename T>
  16. void do_dope_stuff(int arg1, std::map<uint32_t, shared_ptr<T>>& my_object){
  17. //do some programmer magic
  18. for (auto &x:my_object) {
  19. cout << x.first<<": ";
  20. x.second->say_hello();
  21. }
  22. }
  23.  
  24. int main() {
  25. std::map<uint32_t, shared_ptr<parent_class>> my_map;
  26. my_map[777]=make_shared<parent_class>();
  27. my_map[911]=make_shared<child_class>();
  28. my_map[89]=make_shared<parent_class>();
  29. do_dope_stuff(1, my_map);
  30.  
  31. cout << endl<<"second try:"<<endl;
  32. std::map<uint32_t, shared_ptr<child_class>> his_map;
  33. his_map[888]=make_shared<child_class>();
  34. his_map[912]=make_shared<child_class>();
  35. do_dope_stuff(1, his_map);
  36.  
  37.  
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
89: Hello, I'm parent
777: Hello, I'm parent
911: Hello, I'm child

second try:
888: Hello, I'm child
912: Hello, I'm child