home *** CD-ROM | disk | FTP | other *** search
- From: weeks@hpscit.sc.hp.com (Greg Weeks)
- Date: Wed, 22 Jul 1992 21:03:30 GMT
- Subject: iteration without iterators (and a question)
- Message-ID: <46960006@hpscit.sc.hp.com>
- Organization: Hewlett-Packard, Santa Clara, CA
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!sdd.hp.com!hpscdc!hplextra!hpcc05!hpscit!weeks
- Newsgroups: comp.lang.c++
- Lines: 53
-
- This note is divided into two (brief) independent parts. The first part
- describes a simple iteration protocol. The second part asks for help in
- implementing it. (Readers who just want to be helpful can skip to the
- second part.)
-
- THE ITERATION PROTOCOL
-
- Let `col' be a collection that holds items of type `Item'. Here is a
- very simple iteration protocol:
-
- for (Item *pi = col.first(); pi; pi = col.next(pi)) {
- ...
- // `pi' is the address of an item in the collection.
- }
-
- Only two member functions are used by the iteration. No separate iterator
- class is needed. The iteration code fits nicely into a `for' statement.
- And users can set the item at the current location by assigning to `*pi'.
-
- However, to implement `next', you have to:
-
- 1. Get the "node" that holds the item at address `pi'.
- 2. Get the next node.
- 3. Get the address of the item in the next node.
-
- Steps 2 and 3 are easy. But step 1 is hard.
-
- HOW TO IMPLEMENT?
-
- The problem is:
-
- Given the address of a class object member variable, find the address
- of the class object.
-
- In C, this would be easy. Just make the member variable the first member
- of the structure. Then a pointer to the first member may simply be cast to
- a pointer to the structure. But I don't think this works in C++ for a
- couple of reasons.
-
- First, I don't think the first member of a class is guaranteed to be at the
- same physical address as the class object.
-
- But suppose that it is. Now suppose that the collection class is a
- template parameterized by the node class. What happens if someone derives
- a new node class and uses that to build the collection class? It now seems
- likely the the item member will no longer be at the same physical address
- as the new node object. That's the second reason.
-
- This discussion is leaning in the direction of messy
- implementation-dependent considerations. Is there some nice way to avoid
- this?
-
- Greg Weeks
-