Advertisement
obernardovieira

Push multiple types onto same vector

Aug 8th, 2014
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. //NOT BY ME
  2. // http://stackoverflow.com/questions/13461869/c-push-multiple-types-onto-vector
  3.  
  4.  
  5. #include <iostream>
  6. #include <string>
  7. #include <vector>
  8. #include <memory>
  9.  
  10. class any_type
  11. {
  12. public:
  13.    virtual ~any_type() {}
  14.    virtual void print() = 0;
  15. };
  16.  
  17. template <class T>
  18. class concrete_type : public any_type
  19. {
  20. public:
  21.    concrete_type(const T& value) : value_(value)
  22.    {}
  23.  
  24.    virtual void print()
  25.    {
  26.       std::cout << value_ << '\n';
  27.    }
  28. private:
  29.    T value_;
  30. };
  31.  
  32. int main()
  33. {
  34.    std::vector<std::unique_ptr<any_type>> v(2);
  35.  
  36.    v[0].reset(new concrete_type<int>(99));
  37.    v[1].reset(new concrete_type<std::string>("Bottles of Beer"));
  38.  
  39.    for(size_t x = 0; x < 2; ++x)
  40.    {
  41.       v[x]->print();
  42.    }
  43.  
  44.    return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement