Search code examples
c++templatesvectorshared-ptrpolymorphism

C++ How can I store multiple types in an vector of shared_ptrs?


How can I store in a std::vector multiple shared_ptr each one with a pointer to a different type?

std::vector < ? > vec;
vec.push_back( make_shared<int>(3));
vec.push_back( make_shared<float>(3.14f));

Is there a base polymorphic class that can I use for that task without having to use compiler-specific stuff?


Solution

  • There are a few ways you can do this. I assume you want to store various native types, as you're using int and float.

    1. If your list of types is finite, use boost::variant. e.g.

      std::vector<std::shared_ptr<boost::variant<int, float>>>;
      
    2. If you want to store anything, use boost::any. e.g.

      std::vector<std::shared_ptr<boost::any>>;