Is a list template class needed?

C

cass

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!
 
S

Siemel Naran

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::push_back(smart_pointer_type(newobj.release()));
}
};

Surely, there might be other ways to do it.
 
S

Siemel Naran

Kevin Goodsell said:
Siemel Naran wrote:

I suppose you meant list<C*> here.

Yes. Maybe my wording was excellent, but in the next paragraph I wrote the
following:

Raw pointers would have don't have auto destruct and deep copy, though we
could build that into our container, but what a hassle.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,440
Latest member
YoungBorel

Latest Threads

Top