Boost logo

Boost :

From: scleary_at_[hidden]
Date: 2001-10-23 06:27:25

> I remember occasionally seeing posts about storing objects of the same
> (abstract?) base type, but of different concrete types, in a container.
> This can't be directly done with the standard containers, since all the
> elements have to have the same type structure. The closest we can get is
> use a container of base_type*, dynamically allocate the objects, and
> remember to take care of elements' removal when done.
> We have an "any" type that can hold any type of object (hence the name).
> wonder if we can use this to make a container that seems to hold various
> objects derived from a base type.

Correct me if I'm wrong, but "any" doesn't play well with polymorphic
objects: given a "const base & b", how would you construct an any?
  boost::any a(b); // slices
  boost::any a(b.clone()); // imposes on user

I think a better approach would be:
  std::container_type<boost::shared_ptr<base> >
using dereferencing iterator adapters (so you iterate over "const base &").

Insertion becomes an issue here; I would recommend
  iterator insert(const boost::shared_ptr<base> &);
instead of
  iterator insert(const base &);
because it avoids the slicing problem above. But OTOH, it creates an

Having said that, I've never gone far enough to actually do this -- I just
use containers of shared_ptrs, and then live with ugly constructs like:

I'm just not sure it can be done with 'any' because it preserves type
information; consider:
  struct base { }; struct derived: base { };
  boost::any a(derived());
  base b = boost::any_cast<base>(a); // throws bad_any_cast

But if you have an idea on how it would be possible, I'm all ears!


Boost list run by bdawes at, gregod at, cpdaniel at, john at