Passing iterators into functions

Ali Çehreli acehreli at yahoo.com
Thu Jun 25 08:33:37 UTC 2020


Collection elements are accessed by ranges in D. Although both iterators 
and ranges fundamentally do the same thing (access elements). More 
accurately, ranges correspond to a pair iterators.

On 6/24/20 8:35 PM, repr-man wrote:

 > auto func(R)(R r, size_t width)
 > if(isRandomAccessRange!R)
 > {
 >      return r.chunks(width);
 > }
 >
 > void main()
 > {
 >      int[5] a = [0, 1, 2, 3, 4];
 >      int[5] b = [5, 6, 7, 8, 9];
 >      auto x = func!(int[])(chain(a[], b[]), 5);

Is there a reason why you specify the template argument there?

 > This seems to have to do with the fact that all iterators return their
 > own unique type.

When the element is normally different, there would be no way of using 
one type anyway. This is similar to how vector<int>::iterator is a 
different type from e.g. vector<double>::iterator.

 > Could someone help me understand the reason behind
 > this design

Andrei Alexandrescu has the following article on D's ranges:

   https://www.informit.com/articles/printerfriendly/1407357

 > and how to remedy my situation?

Just don't specify the function template argument and it will work.

Ali



More information about the Digitalmars-d-learn mailing list