fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <functional>
  5.  
  6. //========================================================================
  7. //Reference-wrapping utility functions:
  8.  
  9. /*template<class ContainerType, class ElementType = typename ContainerType::value_type >
  10. std::vector<std::reference_wrapper<ElementType>> RefWrapAsVector(ContainerType &container)
  11. {
  12. //Create a vector of std::reference_wrappers wrapping 'ElementType'
  13. return std::vector<std::reference_wrapper<ElementType>>(std::begin(container), std::end(container));
  14. }*/
  15.  
  16. //And the const version:
  17. template<class BaseType, class ContainerType>
  18. std::vector<std::reference_wrapper<const BaseType>> RefWrapAsVector(const ContainerType &container)
  19. {
  20. //Create a vector of std::reference_wrappers wrapping 'BaseType'.
  21. return std::vector<std::reference_wrapper<const BaseType>>(std::begin(container), std::end(container));
  22. }
  23.  
  24.  
  25. //========================================================================
  26. //Your classes:
  27.  
  28. class Animal
  29. {
  30. public:
  31. virtual void Talk() const { std::cout << "<generic animal noise>" << std::endl; }
  32. };
  33.  
  34. class Cat : public Animal
  35. {
  36. public:
  37. Cat(std::string text) : kittySpeach(text) { }
  38.  
  39. void Talk() const override { std::cout << kittySpeach << std::endl; }
  40.  
  41. private:
  42. std::string kittySpeach;
  43. };
  44.  
  45.  
  46. void ForceAnimalsToTalk(const std::vector<std::reference_wrapper<const Animal>> &animals)
  47. {
  48. for(const Animal &animal : animals)
  49. {
  50. animal.Talk();
  51. }
  52. }
  53.  
  54. //========================================================================
  55.  
  56. int main()
  57. {
  58. //Really just an excuse to add moar cats to teh code.
  59. std::vector<Cat> myCats = {Cat("Meow"), Cat("Purr"), Cat("Meowmeow"), Cat("*yawns adorably*")};
  60.  
  61. ForceAnimalsToTalk(RefWrapAsVector<Animal>(myCats));
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Meow
Purr
Meowmeow
*yawns adorably*