home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ogicse!usenet.coe.montana.edu!decwrl!csus.edu!borland.com!pete
- From: pete@genghis.borland.com (Pete Becker)
- Newsgroups: comp.lang.c++
- Subject: Re: Generic types
- Message-ID: <1992Aug28.163946.497@genghis.borland.com>
- Date: 28 Aug 92 16:39:46 GMT
- Article-I.D.: genghis.1992Aug28.163946.497
- References: <l9scgqINNh7u@exodus.Eng.Sun.COM>
- Sender: news@borland.com (News Admin)
- Organization: Borland International
- Lines: 88
- Originator: pete@genghis.borland.com
-
- In article <l9scgqINNh7u@exodus.Eng.Sun.COM> obourdon@France.Sun.COM (Olivier Bourdon - Sun ICNC) writes:
- >Let's assume I have two different types of objects (classes)
- >//-------------------
- >class complex {
- >public:
- > int i,j;
- > ...
- > void Print();
- >};
- >//--------------------
- >class string
- >public:
- > char *str;
- > ...
- > void Print();
- >};
- >
- >and I also have a double linked list
- >//-----------------
- >class list {
- > void *element;
- > list *next, *prev;
- > void Print();
- >};
- >
- >then I woul like to do something like :
- >void list::Print() {
- > while (this->next!=NULL)
- > this->elem->Print();
- > ...
- >}
- >
-
- There are two (at least) ways to do this, depending on what this list
- class is really supposed to do. If each instance of a list will only hold one
- of these types of objects, then the way to do it is with a template:
-
- class ListBase
- {
- protected:
- void *element;
- list *next, *prev;
- public:
- void insert( void * );
- virtual void Print() = 0;
- };
-
- template <class T> class List : public ListBase
- {
- public:
- void insert( T *item ) { ListBase::insert( item ); }
- void Print();
- };
-
- template <class T> void List<T>::Print()
- {
- ListBase *current = this;
- while( current != 0 )
- {
- cout << *(T *)(current->element) << endl;
- current = current->next;
- }
- }
-
- (Although I'd probably put the iteration in the base class, and use a function
- to actually print the element).
- Or, if this list is going to have to hold both types simultaneously,
- then both types must be derived from a common base class:
-
- class ListElement
- {
- public:
- void show();
- };
-
- class Complex : public ListElement
- {
- ...
- };
-
- class String : public ListElement
- {
- ...
- };
-
- Now the list class should hold pointers to ListElements rather than
- pointers to void.
- --Pete
-