adding properties/methods to AA's?

Bill Baxter dnewsgroup at billbaxter.com
Sun Jul 22 23:00:45 PDT 2007


Alex wrote:
> 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.

You can do such a thing for regular arrays, but I don't think it works
for dicts.

http://www.digitalmars.com/d/arrays.html -- look for "Functions as Array
Properties".  There has long been murmuring about how that should be
applied to all types, not just special-cased for arrays.  Maybe someday,
but as far as I know Walter has never weighed in on the idea of
generalizing it.

Also if you do go the route of making a "serialize" function, be aware
that you can't do function overloading across modules in D, so you need
to put all variations of the "serialize" function in the same file, or
call each one explicitly by the module name where it is implemented, e.g.:

   static import varchar; // has serialize for Variant[char[]]
   static import intint; // has serialize for int[int[]]
   intint.serialize(map);
   varchar.serialize(map2);

Or just give the functions different names to begin with.

--bb


More information about the Digitalmars-d-learn mailing list