fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional> // ****
  4.  
  5. struct object
  6. {
  7. virtual ~object() {}
  8. virtual void display() const = 0 ;
  9. };
  10.  
  11. struct weapon : object
  12. {
  13. explicit weapon( std::string n ) : name(n) {}
  14.  
  15. virtual void display() const override { std::cout << "weapon: " << name << '\n' ; }
  16.  
  17. const std::string name ;
  18. // ...
  19. };
  20.  
  21. struct consumable : object
  22. {
  23. explicit consumable( std::string d ) : desc(d) {}
  24.  
  25. virtual void display() const override { std::cout << "consumable: " << desc << '\n' ; }
  26.  
  27. const std::string desc ;
  28. // ...
  29. };
  30.  
  31.  
  32. int main()
  33. {
  34. weapon BronzeSword ( "bronze sword" ) ;
  35. weapon IronSword ( "iron sword" ) ;
  36. consumable MinorHealth ( "minor health" ) ;
  37. consumable Bread ( "bread" ) ;
  38.  
  39. {
  40. std::vector< object* > inventory ; // option one
  41.  
  42. inventory.push_back( &BronzeSword ) ;
  43. inventory.push_back( &IronSword ) ;
  44. inventory.push_back( &MinorHealth ) ;
  45. inventory.push_back( &Bread ) ;
  46.  
  47. for( auto ptr : inventory ) ptr->display() ;
  48. }
  49.  
  50. std::cout << "\n---------------------------\n\n" ;
  51.  
  52. {
  53. std::vector< std::reference_wrapper<object> > inventory ; // option two
  54.  
  55. inventory.push_back( BronzeSword ) ;
  56. inventory.push_back( IronSword ) ;
  57. inventory.push_back( MinorHealth ) ;
  58. inventory.push_back( Bread ) ;
  59.  
  60. for( const auto& wrapper : inventory ) wrapper.get().display() ;
  61. }
  62. }
  63.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
weapon: bronze sword
weapon: iron sword
consumable: minor health
consumable: bread

---------------------------

weapon: bronze sword
weapon: iron sword
consumable: minor health
consumable: bread