[comp.lang.c++] Smalltalk-like iterator?

jat@xavax.com (John Tamplin) (05/06/90)

In article <763@orthogo.UUCP> basti@orthogo.UUCP (Sebastian Wangnick) writes:
>>In article <1145@acf5.NYU.EDU> jjb3281@acf5.NYU.EDU (Thanbo) writes:
>>>I would like to implement an iterator in C++ that would operate much
>>>like a FOR loop: 
>>>
>>>IntArray v;
>>>v.for(int from_val, int to_val, int increment_amount, { C++ statement });

Why can't you do something like the following:

{
	List		list;
	ListIterator	li;
	ListElem	*le;

	for(li.first(list); le=li(); li.movenext()) {
		...
	}
}

With each of my "abstract" classes like list, queue, stack, etc., I also
build iterator classes for them.  The only problem I have with this approach
is that you have to do ugly casts to get the list elements to the proper
type.  Until parameterized classes comes along, I'm not sure that you can solve
that anyway.

What kind of iteration would you want to do that doesn't involve
initialization, test, and increment steps?  The proposed syntax above 
requires rather sticky syntactical notions of being able to pass an arbitrary
chunk of code as an argument to a member function.  The implementation should
be easy, since the compiler could just make it a hidden function.  But what
do you do if you want to return a value?  All this gets to really wanting
to specify the function type, which you can do today in C++ if you write the
function yourself.  ie:

v.iterate(int from_val, int to_val, int increment_amount, void (*func)());

In summary, I think the current language (although parameterized classes
would certainly be nice) introduces only slight inconvenience in implementing
iterators.
-- 
John Tamplin						Xavax
jat@xavax.COM						2804 S Memorial Parkway
...!uunet!xavax!jat					Huntsville, AL 35801