AA with immutable values
    Ali Çehreli 
    acehreli at yahoo.com
       
    Sun Jun 24 05:15:03 PDT 2012
    
    
  
On 06/24/2012 04:57 AM, Roman D. Boiko wrote:
> immutable(SomeClass)[S] _map;
> _map[S.init] = null; // doesn't compile since _map[S.init] is immutable
>
> My current workaround is:
> immutable(SomeClass)*[S] _map;
> _map[S.init] = [null].ptr;
>
> But this introduces an additional level of indirection in a
> performance-critical part of my code.
>
> Probably I could cast away immutable before storing, and cast back to
> immutable after retrieving. But I would be more happy without these two
> casts. (By the way, is it correct that this way would be more efficient?)
>
> Is there any other way to put immutable values into a dictionary?
Although it sounds like a limitation, it may be due to the fact that AA 
may need to rehash, which may not be suitable with immutable values.
The following are two ways of generating immutable AA values that I can 
think of:
import std.exception;
class SomeClass
{}
class S
{}
void main()
{
     /* By initialization */
     immutable(SomeClass)[S] _map = [ S.init : null ];
     /* By a function */
     immutable(SomeClass[S]) makeMap()
     {
         SomeClass[S] result;
         result[S.init] = null;
         return assumeUnique(result);
     }
     /* Note that the entire AA is immutable: */
     auto myImmMap = makeMap();
}
Ali
    
    
More information about the Digitalmars-d-learn
mailing list