Array toHash()

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 26 16:40:06 PST 2014


On 11/26/2014 04:25 PM, David Held wrote:

 > class Foo
 > {
 >      override
 >      size_t toHash() @trusted pure const nothrow
 >      {
 >          // error: no property 'toHash' for type 'int[]'
 >          return importantStuff.toHash();
 >      }

The getHash() member function of the particular TypeInfo can be used. 
However, it is not currently pure, so you must comment that out from 
your toHash:

     override
     size_t toHash() @trusted /* pure */ const nothrow
     {
         return typeid(importantStuff).getHash(&importantStuff);

     }

If a function can safely be casted to pure, you can use the following 
yet-missing-in-phobos function template:

import std.traits;

auto assumePure(T)(T t)
     if (isFunctionPointer!T || isDelegate!T)
{
     enum attrs = functionAttributes!T | FunctionAttribute.pure_;
     return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t;
}

// ...

     override
     size_t toHash() @trusted pure const nothrow
     {
         auto func = assumePure(&(typeid(importantStuff).getHash));
         return func(&importantStuff);
     }

Note that now your toHash can be pure.

Ali



More information about the Digitalmars-d-learn mailing list