Adding different objects to std::list
can you开发者_如何学运维 add different class objects to same list?
See boost::any.
You can use std::vector and then use it to add heterogeneous types into.
Example:
std::vector<boost::any> v;
v.push_back(std::string("hello world"));
v.push_back(42);
No, if they are unrelated objects. If they are related (i.e. have a common base class) then you can store the base class pointer (use smart pointers instead of raw pointers) in the list.
Technically, you could store void *
pointers to objects in your list, but generally it's not a good idea. Better use some "variant" class, such as boost::any
or QVariant
(if you're using Qt) that will wrap your elements.
Only if you derive the objects from the same base class and declare the list of base class type.
精彩评论