www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 13756] New: [AA] Allow ref const index on foreach AA iteration


          Issue ID: 13756
           Summary: [AA] Allow ref const index on foreach AA iteration
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: DMD
          Assignee: nobody puremagic.com
          Reporter: k.hara.pg gmail.com

Currently iterating AA on foreach disallows taking key value by ref.

void main()
    int[int] aa = [1:2];
    foreach (    k,     v; aa) {}
    foreach (    k, ref v; aa) {}
    foreach (ref k,     v; aa) {}   // NG
    foreach (ref k, ref v; aa) {}   // NG

This is intended behavior to disallow the key object mutation stored in the
hidden AA slot, but it has a drawback that we cannot avoid copying key objects
in each iterations.

For the efficiency, I'd propose to allow taking key object by ref const.

void main()
    int[int] aa = [1:2];

    // typeof(k) == const(int)
    foreach (ref k, v; aa) {}

    // Error: index must be type const(int), not int
    //foreach (ref int k, v; aa) {}

    // OK
    foreach (ref const int k, v; aa) {}

Nov 20 2014