home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!devnull!rgp
- From: rgp@mpd.tandem.com (Ramon Pantin)
- Newsgroups: comp.lang.c++
- Subject: Re: tagged unions, an alternative to RTTI (Re: run-time type checking)
- Message-ID: <2157@devnull.mpd.tandem.com>
- Date: 31 Jul 92 02:34:12 GMT
- References: <BryL9q.K5I@watcgl.waterloo.edu> <1992Jul28.183746.24287@ucc.su.OZ.AU> <TMB.92Jul29125322@arolla.idiap.ch>
- Sender: news@devnull.mpd.tandem.com
- Organization: Tandem Computers, Micro-Products Division
- Lines: 58
-
- In article <TMB.92Jul29125322@arolla.idiap.ch> tmb@idiap.ch writes:
- >In article <1992Jul28.183746.24287@ucc.su.OZ.AU> maxtal@extro.ucc.su.OZ.AU (John MAX Skaller) writes:
- > >Consider the classic "List" class and "ListNode" class.
- > >ListNode is a base class, and assume there are two flavors
- > >of derived node. We write a List that contains a mix of
- > >these nodes out to a file; now we want to read the List back
- > >in and reconstruct it.
- ...
- > a) without some type information, it cant be done.
- > b) without casting it can (and should :-) be done
- >
- > union hetero {
- > type1 *p1;
- > type2 *p2;
- > };
- > And the list is homogeneous--all the elements are of type 'hetero'.
- >It would, in fact, be nice if C++ had a tagged union type, like Pascal
- >or SML. Something along the lines of:
- >
- >union hetero int {
- >case 1: type1 *p1;
- >case 2: type2 *p2;
- >};
- >
- >int f(hetero h) {
- > switch(h) {
- > case 1: return h.p1->foo();
- > case 2: return h.p2->bar();
- > }
- >}
- ...
-
- The problem with this style of programming is that it goes
- against the object oriented programming principles. Whenever
- you use unions of different representations of objects that
- are "similar" (instead of having a virtual base class and multiple
- classes derived from it) and the code that manipulates each type
- of object is located inside a bunch of switch statements spread all
- over your code you end up with traditional procedural programming
- not with OOP.
-
- When you ask, where is all the code that manipualtes an "hetero"
- of "type1"? You have to go searching for all those switches. What is
- even worse, when you need to _add_ anoter type to your "hetero" union
- (instead of simply deriving another class from your base class in OOP)
- then you have to find all the switches and change them. Instead of
- writting and testing a new ".o" file that implements your new class
- you have to change all your old code that contains the switches and
- re-test it.
-
- Another general problem with unions is that when you add another
- field to your union it might grow. If you have instances of your
- unions stored somewhere (say on a file, from a previous incarnation
- of your program) then the new version of the program (where the union
- grew) will have know about the size change and have to deal with the
- old and new sizes of the union.
-
- Ramon Pantin
-