bearophile <bearophileh...@lycos.com> 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?

Definitely worth adding to bugzilla. I can't find the post now, but there
is a good description of how foreach loops can be rewritten as for loops,
with type inference. Further testing shows that 'auto' creates the same
problems, so it seems foreach is simply magical.

--
Simen

Reply via email to