Getting the const-correctness of Object sorted once and for all

Era Scarecrow rtcvb32 at yahoo.com
Tue May 15 15:33:54 PDT 2012


On Tuesday, 15 May 2012 at 21:18:11 UTC, Chad J wrote:
> On 05/15/2012 03:32 PM, Chris Cain wrote:
> Yep, ya got me.
>
>>
>> Maybe there's a solution, but I doubt the solution is something
>> the programmer can/should do completely transparently.

  Perhaps an alternate workaround... a thought coming to mind, is 
that the constructor for a const object lets you set it once in 
the constructor (but not touch it again after) So.... Maybe...?

class X {
   uint cached_hash;

   this() {

     cached_hash = X.toHash(this); //last line, only if we can 
send 'this'
   }

   static uint toHash(const X x) {
     return hashedResult;
   }

   uint toHash(){
     return X.toHash(this);
   }

   uint toHash() const {
     return hash;
   }
}

  Although there's a lot there, with a const and non-const version 
the const version is optimized and always returned the proper 
precalculated hash, and if it isn't it creates it on the fly as 
appropriate.

  You'd almost say an interface you can attach would be the way to 
get the same basic functionality with minimal effort. So maybe... 
Perhaps a template is better used. Mmm....

interface CachedHash(T) {
   private uint cachedHash;

   //your hashing function
   static uint toHash(T);

   //call from constructor
   private void setHash() {
     cachedHash = T.toHash(this);
   }
   uint toHash() const {
     return cachedHash;
   }

   override uint toHash() {
     return T.toHash(this);
   }
}

  You should get the basic idea. Same thing would be done for 
toString with a cached result.


More information about the Digitalmars-d mailing list