home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16633 < prev    next >
Encoding:
Text File  |  1992-11-20  |  2.2 KB  |  69 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!munnari.oz.au!metro!extro.ucc.su.OZ.AU!maxtal
  3. From: maxtal@extro.ucc.su.OZ.AU (John MAX Skaller)
  4. Subject: Re: BC++ Container Class Problem
  5. Message-ID: <1992Nov20.135225.29078@ucc.su.OZ.AU>
  6. Sender: news@ucc.su.OZ.AU
  7. Nntp-Posting-Host: extro.ucc.su.oz.au
  8. Organization: MAXTAL P/L C/- University Computing Centre, Sydney
  9. References: <1992Nov16.014419.27027@ntuix.ntu.ac.sg>
  10. Date: Fri, 20 Nov 1992 13:52:25 GMT
  11. Lines: 56
  12.  
  13. In article <1992Nov16.014419.27027@ntuix.ntu.ac.sg> gthkoh@ntuix.ntu.ac.sg (Koh Thong Hwee) writes:
  14. >
  15. >In particular, I would like to know how to use the link list to store
  16. >disparate objects.  I can use the indirect storage method of storing their
  17. >pointers instead.  However I need to declare the type T for the link list
  18. >template class and how do I declare it for storing the different pointer types
  19. >to the many different kinds of objects? 
  20. >
  21.  
  22.     The best way to do this is with tagged pointers ... but thats
  23. only a proposal of mine, so here's roughly how to emulate this facility.
  24.  
  25.     Suppose you want to but pointers to A,B and C objects in the list.
  26. (Or an array, or other container). Well, you cant, you can only put objects
  27. of a single type in a container.
  28.  
  29.     struct ABC {
  30.         enum {A_t, B_t, C_t} tag;
  31.         union {
  32.             A* a;
  33.             B* b;
  34.             C* c;
  35.         };
  36.         ABC(A* aa) {a=aa; tag=A_t;}
  37.         ABC(B* bb) {b=bb; tag=B_t;}
  38.         ABC(C* cc) {c=cc; tag=C_t;}
  39.     };
  40.  
  41. Now put ABC objects in the list. Use them like this:
  42.  
  43.     ABC abc;
  44.     ...
  45.     switch(abc.tag)
  46.     {
  47.     case A_t: a->print(); ...
  48.     case B_t: b->print(); ...
  49.     case C_t: c->print(); ...
  50.     }
  51.  
  52. This mechanism would be completely automated using tagged pointers:
  53.  
  54.     [A,B,C] *abc;
  55.     abc->print();
  56.  
  57. The method does NOT require any casts, it is 'type-safe' by not secure
  58. in that you might select the wrong union member. However using casts
  59. is far worse, you might cast to anything. Tagged pointers, however
  60. are completely secure (since the tag checking code is compiler generated).
  61.  
  62.  
  63.  
  64. -- 
  65. ;----------------------------------------------------------------------
  66.         JOHN (MAX) SKALLER,         maxtal@extro.ucc.su.oz.au
  67.     Maxtal Pty Ltd, 6 MacKay St ASHFIELD, NSW 2131, AUSTRALIA
  68. ;--------------- SCIENTIFIC AND ENGINEERING SOFTWARE ------------------
  69.