Ranges: is it ok if front is a data member?

Ali Çehreli acehreli at yahoo.com
Thu Dec 12 13:55:20 PST 2013


On 12/12/2013 12:06 PM, H. S. Teoh wrote:
> On Thu, Dec 12, 2013 at 08:12:50PM +0100, Jesse Phillips wrote:
>> On Thursday, 12 December 2013 at 16:52:12 UTC, Joseph Rushton
>> Wakeling wrote:
>>> On 12/12/13 17:19, Adam D. Ruppe wrote:
>>>> Is that guaranteed to work as an input range? I ask because I've
>>>> so often written:
>>>>
>>>>   T current;
>>>>   @property T front() { return current; }
>>>>
>>>> that it just seems silly to me to write the extra lines when current
>>>> == front. I realize there is a small difference there, in that front
>>>> is not an lvalue here, but is when it is a direct member, but other
>>>> than that, is this an acceptable form? Or does the lvalue thing mean
>>>> it is strongly discouraged?
>>>
>>> Isn't the issue here not whether or not it will work in terms of your
>>> type being a range, and more that it means that users can overwrite
>>> the value of front?
>>>
>>> It seems to me that it would be OK for personal projects where you
>>> control 100% of the code, but it wouldn't be acceptable for stuff
>>> that's intended to be used by other people.
>>
>> Being able to assign to front is a feature of an output range.
>
> Really?? I thought the defining feature of an output range is the .put
> method.
>
>
> T
>

The third condition that is checked to determine whether it is an 
OutputRange is indeed assignment to front.

   http://dlang.org/phobos/std_range.html#.put

That condition is what makes a slice an OutputRange, which causes the 
super confusing state of "output range losing elements after put'ting": :)

import std.range;

void main()
{
     auto s = [ 1, 2, 3 ];
     s.put(10);
     assert(s.length == 2); // PASSES! :p
}

Ali



More information about the Digitalmars-d-learn mailing list