Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Mon Dec 12 11:33:46 PST 2011


On Monday, December 12, 2011 12:13:54 Kai Meyer wrote:
> On 12/10/2011 03:52 AM, Timon Gehr wrote:
> > On 12/10/2011 11:45 AM, bearophile wrote:
> >> Timon Gehr:
> >>> Just slice the const array to get a range. The specialization for
> >>> ranges does not have the bug.
> >>> 
> >>> import std.algorithm;
> >>> void main() {
> >>> const arr = [1, 2, 3];
> >>> reduce!"a*b"(arr[]); // It works.
> >>> }
> >> 
> >> Wasn't arr a range already?
> >> 
> >> Bye,
> >> bearophile
> > 
> > No, popFront is mutating and const(int[]) cannot be mutated.
> 
> Seems to me like popFront isn't the right tool for the job.

??? That's how you iterate a range. Without it, a range is essentially 
useless. There _is_ no other tool for the job.

Ranges _could_ have been designed more like slists and use head and tail and 
avoid needing to be mutated, but that's less efficient, since you have to copy 
the range every time that you iterate to the next item.

Generally, the way to solve the issue of a const or immutable range is to get 
a tail-const copy of it. With arrays, that's easy - just slice it. With user-
defined ranges, it requires that opSlice be defined that way, which it may or 
may not be.

But you can't iterate over a const range anymore than you can iterate over a 
const iterator in C++. In both cases, you need a non-const copy if you want to 
iterate. There's nothing odd about it really. It's just that templates take 
the _exact_ type with IFTI and so don't generally work with const or immutable 
ranges. The proposed change to make arrays instantiate templates with their 
tail-const type with IFTI will fix that for arrays though.

- Jonathan M Davis


More information about the Digitalmars-d mailing list