Primary Ranges of Containers

Matthias Walter xammy at xammy.homelinux.net
Wed Jun 20 03:29:49 PDT 2012


On 06/19/2012 04:04 PM, Timon Gehr wrote:
> On 06/19/2012 02:54 PM, Christophe Travert wrote:
>> Jonathan M Davis , dans le message (digitalmars.D:170054), a écrit :
>>>> I'd propose to always add a bool template parameter (maybe isConst?) to
>>>> the range since most of the write-functionality can be "removed" by a
>>>> static if statement in order to make the range read-only.
>>>>
>>>> Any suggestions?
>>
>> Boolean parameters are very obscure.
>> How do you guess what is the meaning of false in:
>> Range!false;
>>
>> Range!IsConst.no would be better.
>>
>>> struct ArrayRange(bool isConst) {...}
>>> alias ArrayRange!false Range;
>>> alias ArrayRange!true ConstRange;
>>
>> Range and ConstRange seems a good thing to have, just like c++
>> containers have iterator and const_iterator.
>>
> 
> Something along these lines seems to be a superior design:
> 
> struct ArrayRange(T){ ... }
> 
> class Array(T){
>     ...
>     ArrayRange!T opSlice(){ ... }
>     ArrayRange!(const(T)) opSlice()const{ ... }
>     ArrayRange!(immutable(T)) opSlice()immutable{ ... }
>     ...
> }
> 
> (Where the opSlice functions can be generated automatically.)

I like the design. I looked at the actual implementation of
std.container.Array and realized the following problem:

The payload is stored in a RefCounted object. The range returned by
opSlice() const must obviously somehow access the payload. By
documentation of RefCounted, "no references to the payload should be
escaped outside the RefCounted object." which implies that we need to
create a copy of the RefCounted variable to have proper access.

On the other hand, given the constness of opSlice() we only have access
to a const version of the RefCounted variable which cannot be used to
create another reference since the reference counter is const as well.

So how can a ConstRange be implemented *somehow*?

Matthias


More information about the Digitalmars-d mailing list