Const foreach

bearophile bearophileHUGS at
Sun Nov 21 17:21:14 PST 2010

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?

Bye and thank you,

More information about the Digitalmars-d-learn mailing list