fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class Base {};
  6. class A : public Base{};
  7. class B : public Base{};
  8. class C : public Base{};
  9.  
  10. class CollectionOfBase
  11. {
  12. public:
  13. void add (std::shared_ptr<Base> item){m_items.push_back(item);}
  14. std::vector<std::shared_ptr<Base>> const& getItems() const {return m_items;}
  15.  
  16. private:
  17. std::vector<std::shared_ptr<Base>> m_items;
  18. };
  19.  
  20. void identify( std::shared_ptr<A> const& )
  21. {
  22. std::cout << "A" << std::endl;
  23. }
  24.  
  25. void identify( std::shared_ptr<B> const& )
  26. {
  27. std::cout << "B" << std::endl;
  28. }
  29.  
  30. void identify( std::shared_ptr<C> const& )
  31. {
  32. std::cout << "C" << std::endl;
  33. }
  34.  
  35. //This function works in the below for loop, but this is not what I need to use
  36. void identify( std::shared_ptr<Base> const& )
  37. {
  38. std::cout << "Base" << std::endl;
  39. }
  40.  
  41.  
  42. int main()
  43. {
  44. using namespace std;
  45.  
  46. CollectionOfBase collection;
  47.  
  48. collection.add(make_shared<A>());
  49. collection.add(make_shared<A>());
  50. collection.add(make_shared<C>());
  51. collection.add(make_shared<B>());
  52.  
  53. for (auto const& x : collection.getItems())
  54. {
  55. // THE QUESTION:
  56. // How to distinguish different type of items
  57. // to invoke "identify" with object specific signatures ???
  58. // Can I cast somehow the object types that I push_back on my vector ???
  59.  
  60. identify(x);
  61. }
  62. /*
  63. The desired output of this loop should be:
  64.  
  65. A
  66. A
  67. C
  68. B
  69.  
  70. */
  71.  
  72. return 0;
  73. }
  74.  
  75.  
Success #stdin #stdout 0s 16056KB
stdin
Standard input is empty
stdout
Base
Base
Base
Base