AA default value?

Oskar Linde oskar.lindeREM at OVEgmail.com
Fri Jan 25 05:57:35 PST 2008


Jarrett Billingsley wrote:
> "Janice Caron" <caron800 at googlemail.com> wrote in message 
> news:mailman.24.1201263099.5260.digitalmars-d at puremagic.com...
> 
>> Wouldn't
>> it be nicer if, instead, it simply returned
>>
>> typeof(aa[key]).init
>>
>> if the key was not present in the array?
> 
> What's funny is that a while ago ((long) before 1.0), if you looked up a key 
> in an AA and the key didn't exist, it'd be added with a value of 
> typeof(aa[key]).init.  So
> 
> int[int] aa;
> writefln(aa[5]);
> 
> would give "0" as the output.
> 
> This was to mirror the behavior of C++'s std::map but many people opposed 
> it, so now we have what we have now..

I believe the implemented solution to the old problem overshoot the best 
solution, which would have been to make a rvalue expression aa[5] return 
0, but *without* inserting 5 into the aa.

I have for ages had the following two simple utility functions in most 
code I write that uses AAs:

T get(T,U)(T[U] aa, U key) {
         T* ptr = key in aa;
         if (ptr)
                 return *ptr;
         return T.init;
}

T get(T,U,int dummy=1)(T[U] aa, U key, lazy T defaultValue) {
         T* ptr = key in aa;
         if (ptr)
         	return *ptr;
        	return defaultValue;
}

and almost always use aa.get(5), instead of aa[5].

> The issue is that you can't cover all the bases with a single type.  Some 
> people want the auto-insertion, some don't.  Some want it to disallow 
> updates, i.e. allow a key-value pair to be inserted but never modified. 
> Some want the opposite, where you have to explicitly use an insert method to 
> insert the values, but once they're in, they can be modified as much as you 
> like.
> 
> At least the nice thing about the AAs is that they're simple to build custom 
> containers on top of them, so most/all of these things can be implemented as 
> structs wrapping them.  The downside is that with the current set of 
> operator overloads and features, you can never make a custom type that can 
> replace the builtin one in all cases. 

The biggest problem with custom containers is the lack of a reference 
return type.

-- 
Oskar



More information about the Digitalmars-d mailing list