Ranges and/versus iterators

Fawzi Mohamed fawzi at gmx.ch
Thu Mar 25 03:32:37 PDT 2010


On 25-mar-10, at 00:09, Fawzi Mohamed wrote:

>
> On 24-mar-10, at 23:29, Andrei Alexandrescu wrote:
>
>> [...]
>> So arrays have a different interface than streams. It looks like  
>> you can't write code that works uniformly for both, because for  
>> some you need the * and for some you don't. Did I understand that  
>> correctly?
>
> well the foreach loop is the same, but the iteration loop is indeed  
> different in the sense that one uses a pointer to an element and the  
> other the element itself.
> one can write code that removes the pointer that is there  
> (dereferencing it, or doing and inline function with subsequent call  
> which allows you to reuse the same variable name):
> void myF(ref x){
> // code
> }
> myF(*x);
>
> (that is a nice trick that I used several times).
>
> But yes there *is* a difference and the difference is that with  
> arrays you might modify the element, modifying the stored value,  
> whereas with streams you can't.
> This conceptual difference and if reflected in the interface.
> One can then discuss if immutable arrays should be iterated with  
> immutable pointers or with values (i.e. copying) just as streams are.

thinking more about this, you are right something that returns a ref  
can be used exactly the same way as something that returns a value if  
one takes the value with
	auto val=returnRefOrVal;
can be used as value exactly in the same way.
Whereas something that returns a T or a T* , need an explicit  
conversion.
That is easy to do, and one can even easily wrap the delegate in place  
with something that returns T instead of T*, but the conversion has to  
be explicit (before feeding it to the code), or explicitly tested for  
in the code.
In practice I hadn't real problems due to this, but it is something  
that is uglier than ref return.
On the other hand it is easier to know if you might modify the value  
that you received expecting to modify the underlying structure.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100325/3d95089e/attachment.html>


More information about the Digitalmars-d mailing list