cnd
cnd

Reputation: 33754

List (vector) of different structs

is it possible to have some kind of list / array / vector of different structs?

For example in MFC there are CObject and CArray but without MFC:

I can do something alike

std::vector<void*> pVec;
{
  MYSTRUCT m = new MYSTRUCT;
  pArr.push_back(m);
  // looks fine here
}
//what is in my vector now?

Is there something that can handle it?

Upvotes: 0

Views: 2006

Answers (2)

quantdev
quantdev

Reputation: 23793

The obvious preferred approach is to have a std::vector<Base*> to handle polymorphic types.

If you really have completely unrelated types, as it seems to be the case, then boost::any or boost::variant type erasers might be what you are looking for :

std::vector< boost::variant<int, std::string> > vec;
vec.push_back( 21 );
vec.push_back( "hello " );

Upvotes: 4

The example that you have given is dangerous. How do you clean up (i.e. delete) what you've allocated? Its type has been erased by being assigned to a void *, so how can the compiler know which operator delete to call?

You can safely go about this at least two different ways:

  • All the objects can inherit from a common base which has a virtual destructor. You can then make a std::vector of std::unique_ptrs to the common base. This has the advantage of being extensible (you can declare new types which derive from the common base and throw them in the container without modifying the container), but has the disadvantage of requiring that you go to the free store (to allocate memory for the std::unique_ptrs to point to).
  • You can use a variant type like boost::variant. This will not require a common base, or allocations on the free store, but it will require that you declare all the types that can possibly be stored in the container when you declare the container (i.e. it's not as easily extensible as an inheritance-based solution).

Upvotes: 2

Related Questions