home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!noc.near.net!hri.com!spool.mu.edu!sol.ctr.columbia.edu!emory!swrinde!cs.utexas.edu!convex!news.utdallas.edu!corpgate!crchh327!bnr.ca!holiday
- From: holiday@bnr.ca (Matthew Holiday)
- Newsgroups: comp.lang.c++
- Subject: Re: Discriminating Variant Records Without switch() ??
- Message-ID: <1992Nov11.144253.26415@bnr.ca>
- Date: 11 Nov 92 14:42:53 GMT
- References: <BAB.92Nov10073324@se39.wg2.waii.com>
- Sender: holiday@crchh82 (Matthew Holiday)
- Reply-To: holiday@bnr.ca
- Organization: Bell-Northern Research, Richardson, TX
- Lines: 38
- Nntp-Posting-Host: crchh82
-
- In article <BAB.92Nov10073324@se39.wg2.waii.com>, bab@se39.wg2.waii.com (Brian Button) writes:
- |> Is there a simple, OOP based way to discriminate between variant
- |> records? I saw an article in C Users Journal last month titled "Switch
- |> Deemed Harmful to C++" or something like that, but I couldn't figure
- |> out how to do it any other way.
- |>
- |> As an example:
- |>
- |> We're reading structures sent to us over a socket. Since these
- |> structures are being sent and received on the same machine, we can
- |> just memcpy the byte stream read from the socket into a big union, and
- |> then switch based on the first field of the union to determine the type.
- |>
- |> [text ommitted]
- |>
- |> This works, but doesn't look very OOP-ish. Can anyone give me any
- |> suggestions about how this can be reformed to fit in with the object
- |> paradigm and not use the switch statement?
-
- Another (not quite OOP-ish) way is to have an array of function pointers,
- and index the array with the first field of the union. Note that you need
- an appropriate nil function for all the array entries which represent invalid
- indices. This is pretty straightforward.
-
- The OOP-ish way would be to construct an object of the appropriate class to
- match your input message, and then call that object's methods (which would
- be overridden as necessary for specific subclasses). Unfortunately, the
- part of your code where you construct the object is likely to be non-OOP-ish,
- in fact, it'll probably require a switch statement! :-) There ought to be a
- convenient way to create objects from network messages, i.e., some way to
- register message types and their matching class types, such that for every
- incoming message, its body (an array of bytes) gets turned into the correct
- object, which would be derived from a root generic message object.
-
- --
- Matt Holiday #include <std/disclaimer>
- holiday@bnr.ca
- BNR Richardson, TX
-