www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - [Suggestion] .toHash and .toString on built-in types

I've noticed that the hashmap template I created a while back only works 
with struct/union/class types and not with primitive/array/pointer types.

Basically, we have a limitation on the generic programming side: the 
.toHash property is only definable on struct/union/class types, and 
doesn't exist on built-in ones.  I cannot change it to dig into 
TypeInfo, since half the point of my template is to be a workaround for 
the failings of D's AAs.  TypeInfo hacking is a rather down and dirty 
approach anyway; even once the shortfalls are dealt with, key.toHash 
will remain a nicer notation than typeid(KeyType).getHash(&key).

The .toHash property would correspond to the existing hash function for 
the relevant type.  The only issue I see is what should happen with 
pointer types.  Possibilities I can see are:

(a) Keep TypeInfo_P.getHash returning the memory address, and have 
pointer.toHash follow this convention.  But this would make an exception 
to the rule that pointer.anything is equivalent to (*pointer).anything.

(b) Redefine the hash of a pointer (except void*) to be equal to the 
hash of the dereferenced data.  Not sure if this would be the Right 
Thing, as any container that uses pointers as keys would be invalidated 
if the data they point to is modified.

(c) Keep the TypeInfo (and hence the behaviour in built-in AAs) as it 
is, but nonetheless have pointer.toHash equivalent to (*pointer).toHash. 
  This wouldn't break existing code, but would require that a given 
template consistently uses either .toHash or TypeInfo.getHash.

And this is before you get back into arguing over the propriety of using 
memory addresses as hash values.

Similarly, every type having a .toString property might be handy, and it 
would correspond to the behaviour of the "%s" format specifier on the 
type involved.  Well, maybe open to the same debates....

Just thinking about it, I guess it's a matter of debate whether these 
features would really achieve anything over fixing some bugs....

Nov 15 2004