home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!munnari.oz.au!metro!extro.ucc.su.OZ.AU!maxtal
- From: maxtal@extro.ucc.su.OZ.AU (John MAX Skaller)
- Subject: Re: BC++ Container Class Problem
- Message-ID: <1992Nov20.135225.29078@ucc.su.OZ.AU>
- Sender: news@ucc.su.OZ.AU
- Nntp-Posting-Host: extro.ucc.su.oz.au
- Organization: MAXTAL P/L C/- University Computing Centre, Sydney
- References: <1992Nov16.014419.27027@ntuix.ntu.ac.sg>
- Date: Fri, 20 Nov 1992 13:52:25 GMT
- Lines: 56
-
- In article <1992Nov16.014419.27027@ntuix.ntu.ac.sg> gthkoh@ntuix.ntu.ac.sg (Koh Thong Hwee) writes:
- >
- >In particular, I would like to know how to use the link list to store
- >disparate objects. I can use the indirect storage method of storing their
- >pointers instead. However I need to declare the type T for the link list
- >template class and how do I declare it for storing the different pointer types
- >to the many different kinds of objects?
- >
-
- The best way to do this is with tagged pointers ... but thats
- only a proposal of mine, so here's roughly how to emulate this facility.
-
- Suppose you want to but pointers to A,B and C objects in the list.
- (Or an array, or other container). Well, you cant, you can only put objects
- of a single type in a container.
-
- struct ABC {
- enum {A_t, B_t, C_t} tag;
- union {
- A* a;
- B* b;
- C* c;
- };
- ABC(A* aa) {a=aa; tag=A_t;}
- ABC(B* bb) {b=bb; tag=B_t;}
- ABC(C* cc) {c=cc; tag=C_t;}
- };
-
- Now put ABC objects in the list. Use them like this:
-
- ABC abc;
- ...
- switch(abc.tag)
- {
- case A_t: a->print(); ...
- case B_t: b->print(); ...
- case C_t: c->print(); ...
- }
-
- This mechanism would be completely automated using tagged pointers:
-
- [A,B,C] *abc;
- abc->print();
-
- The method does NOT require any casts, it is 'type-safe' by not secure
- in that you might select the wrong union member. However using casts
- is far worse, you might cast to anything. Tagged pointers, however
- are completely secure (since the tag checking code is compiler generated).
-
-
-
- --
- ;----------------------------------------------------------------------
- JOHN (MAX) SKALLER, maxtal@extro.ucc.su.oz.au
- Maxtal Pty Ltd, 6 MacKay St ASHFIELD, NSW 2131, AUSTRALIA
- ;--------------- SCIENTIFIC AND ENGINEERING SOFTWARE ------------------
-