|
#1
|
|||
|
|||
|
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! |
|
#2
|
|||
|
|||
|
"cass" <casscure@knowhouse.com> wrote in message news:mIHgc.51170
> 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.rel ease())); } }; Surely, there might be other ways to do it. |
|
#3
|
|||
|
|||
|
Siemel Naran wrote:
> "cass" <casscure@knowhouse.com> wrote in message news:mIHgc.51170 > > >>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. I suppose you meant list<C*> here. -Kevin -- My email address is valid, but changes periodically. To contact me please use the address from a recent posting. |
|
#4
|
|||
|
|||
|
"Kevin Goodsell" <usenet2.spamfree.fusion@neverbox.com> wrote in message
news:HwKgc.2081 > Siemel Naran wrote: > > If you use a list<C> you can hold both A and B objects in the same list. > > I suppose you meant list<C*> here. Yes. Maybe my wording was excellent, but in the next paragraph I wrote the following: >>Actually, in C++ you have to use something like >>std::list<boost::shared_ptr<C> > and ensure that C::~C() is virtual. Raw pointers would have don't have auto destruct and deep copy, though we could build that into our container, but what a hassle. |
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|