Const foreach
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 21 17:59:09 PST 2010
On Sunday 21 November 2010 17:21:14 bearophile wrote:
> If in a D2 program I have an array of mutable items I may want to iterate
> on them but not modify them, so I'd like the iteration variable to be
> const. This is possible, but it seems I lose type inference:
>
>
> void main() {
> int[3] array; // not const
> // foreach (const x; array) {} // Error
> // foreach (const auto x; array) {} // Error
> // foreach (const(int) x; array) {} // OK
> foreach (const(typeof(array[0])) x; array) {} // OK
> }
>
>
> Is something wrong in that code? Is this a known limitation, an inevitable
> one? Is this an enhancement request worth adding to Bugzilla?
Actually, const is pointless in your example, since you're dealing with a value
type. Where it would matter is if you were dealing with an element type which
was a reference type or if you marked x as a ref. And unfortunately, I don't
think that it works to use const ref in a foreach (I've never gotten it work
anyway) - probably for the same reason that const ref won't take an lvalue (and
I _really_ wish that it would). _That_ would likely be worth opening up an
enhancement request for, and it's probably necessary to get foreach to work
properly with const.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list