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?
C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
Use shared_ptr to manage the lifetime of objects: Whose ownership is shared (multiple "things" want the object lifetime extended) Where the order of release of ownership is non-deterministic (you don't know in advance which of the owners will be "last" to release the object).
Description. It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.
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.
If your list of types is finite, use boost::variant. e.g.
std::vector<std::shared_ptr<boost::variant<int, float>>>;
If you want to store anything, use boost::any. e.g.
std::vector<std::shared_ptr<boost::any>>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With