"cass" <ca******@knowh ouse.com> wrote in message news:mIHgc.5117 0
Both class A and B inherites from class C. A std::list is used to contain
a list of objects of class A or a list of objects of class B, but not both
types of classes at the same time.
How to use template to realize this? Thanks!
If you use a list<C> you can hold both A and B objects in the same list.
But you don't have to take advantage of this -- ie. you can set it up so
that all the objects will be A or all will be B.
Actually, in C++ you have to use something like
std::list<boost ::shared_ptr<C> > and ensure that C::~C() is virtual.
In your list insert function you can enforce all items have the same type.
class mylist : private std::list<boost ::shared_ptr<C> > {
typedef boost::shared_p tr<C> smart_pointer_t ype;
typedef std::list<smart _pointer_type> list_base;
public:
class inconsistent_ty pe { };
typedef list_base::size _type size_type;
size_type size() const { return list_base::size (); }
C& back() { return *list_base::bac k(); }
const C& back() const { return *list_base::bac k(); }
void push_back(std:: auto_ptr<C> newobj) {
if (size()) {
if (typeid(back() != typeid(*newobj) ) throw inconsistent_ty pe();
}
list_base::push _back(smart_poi nter_type(newob j.release()));
}
};
Surely, there might be other ways to do it.