adding properties/methods to AA's?

Bill Baxter dnewsgroup at billbaxter.com
Mon Jul 23 16:48:07 PDT 2007


Oskar Linde wrote:
> Alex skrev:
>> Ok, so I've got a property (I guess that's the proper term to use?) 
>> that I'd like to be able to use with any AA declared as 
>> Variant[char[]].  For example, I'd like to be able to do the following.
>>
>> Variant[char[]] map;
>> ubyte []stream;
>>
>> stream = map.serialize;
>> map.deserialize( stream );
>>
>> int [int[]] map2;
>> stream = map.serialize; //invalid, int [int[]] does not have serialize 
>> property.
>>
>> Is this even possible?  I'm sure someone will tell me to just write a 
>> function such as ubyte []serialize( Variant[char[]]input ), and I'm 
>> aware this is an option.  I just think the above looks a bit more slick.
> 
> just write the function as ubyte[] serialize(Variant[char[]] input) and 
> call it as:
> 
> map.serialize(); // Note, the trailing pair of empty parentheses

Hey you're right!  I forgot that AA's work that way too.  I had this 
little test function in my tests directory that didn't work at some 
point but now apparently it does:

V get(V,K)(V[K] dict, K key, V def = V.init)
{
     V* ptr = key in dict;
     return ptr? *ptr: def;
}


void main()
{
     char[][int] i2s;
     i2s[1] = "Hello";
     i2s[5] = "There";

     writefln( i2s.get(1, "yeh") );
     writefln( i2s.get(2, "default") );
     writefln( i2s.get(1) );
}

Boffo!

--bb


More information about the Digitalmars-d-learn mailing list