cass said:
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_ptr<C> smart_pointer_type;
typedef std::list<smart_pointer_type> list_base;
public:
class inconsistent_type { };
typedef list_base::size_type size_type;
size_type size() const { return list_base::size(); }
C& back() { return *list_base::back(); }
const C& back() const { return *list_base::back(); }
void push_back(std::auto_ptr<C> newobj) {
if (size()) {
if (typeid(back() != typeid(*newobj)) throw inconsistent_type();
}
list_base:
ush_back(smart_pointer_type(newobj.release()));
}
};
Surely, there might be other ways to do it.