Iterators for D

Sean Kelly sean at f4.ca
Tue Nov 7 05:56:46 PST 2006


Walter Bright wrote:
> Sean Kelly wrote:
>> Is there really any reason to support pointers as iterators though?  
>> C++ libraries even seem to be moving away from that towards more 
>> robust and less error-prone iterator objects.
> 
> Can you be more specific about what the problems and solutions are?

A direct application of pointers as iterators couldn't be done exactly 
the C++ way because C++ uses traits templates to describe the operations 
an iterator supports.  And D will not overload templates from different 
modules, so the user could not provide overloads for his own iterators. 
  This isn't a huge problem however, as we could probably write a set of 
generic traits templates that apply to classes/structs implemented the 
'right' way rather than requiring the user to provide his own.  This 
would be roughly similar to how a user can derive from std::iterator<> 
to add the required typedefs to his object in C++.

More generally though, I find the need to use two iterators to identify 
a range to be somewhat cumbersome and annoying.  And there have been 
enough others who feel this way that there has been at least an informal 
proposal for "all in one" iterators for C++.  I haven't bothered to 
check whether it was ever formalized though.

Basically, I'm wondering whether it might be easier and more D-like to 
use iterators for stepping and opIndex for random access, instead of 
iterators for everything.  Since D has slicing, the argument for using 
iterators to define the boundaries of a range of randomly accessible 
elements seems kind of small to me.  ie.

     sort( a.begin, a.begin + 5 ); // sort the first 5 elements
or
     sort( a[0 .. 5] );

I find the second to be cleaner to look at.  But I'm undecided whether 
we'd lose any power or flexibility by not bothering with random access 
iterators.


Sean



More information about the Digitalmars-d mailing list