Primary Ranges of Containers

Jonathan M Davis jmdavisProg at gmx.com
Mon Jun 18 04:08:50 PDT 2012


On Monday, June 18, 2012 10:06:44 Matthias Walter wrote:
> Hi,
> 
> last week I realized that a const version of
> std.container.Array.opSlice() is missing. Now I looked at the code and I
> think that it is a general design problem.
> 
> The docs state that "c.Range" is "The primary range type associated with
> the container.". I think we really always need two Range types (one for
> const view and one for non-const view) by design.
> 
> 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?

Yeah, it'll probably have to be templated. C++ already has to do something 
similar with iterators and const_iterators. But since you don't normally use 
the type of a range explicitly, it shouldn't be a big deal. The one downside 
that might pose a problem though is that if someone _does_ use the type 
explicitly, their code will break if the type gets templated. We could make a 
second type (ConstRange?) for the iterating over a const Array, but I'd be 
tempted to just templatize the thing and let it break any code that it breaks. 
std.container is already likely to break stuff to at least some extent when the 
custom allocators get added anyway. I suppose that we could just rename the 
type and then create an alias for the current type

struct ArrayRange(bool isConst) {...}
alias ArrayRange!false Range;
alias ArrayRange!true ConstRange;

but that might be overkill. I don't know. Regardless, it _is_ likely that the 
range type will have to be templatized to fix the problem. Ranges and range-
based functions in general need to be cleaned up a bit to deal with const, 
since the way that they're designed doesn't work with const very well, and we 
need to make it work. I think that it _can_ work, but it takes more effort to 
do so.

- Jonathan M Davis


More information about the Digitalmars-d mailing list