How use "toHash" without cast

Jonathan M Davis jmdavisProg at gmx.com
Thu Jun 21 01:47:18 PDT 2012


On Thursday, June 21, 2012 09:48:52 Namespace wrote:
> > It's actually @trusted as per the docs. I do not know why DMD
> > infers that to be @safe.....
> > 
> > In any case, the solution here is this:
> >     override hash_t toHash() @trusted const pure nothrow {
> >     
> >         return cast(hash_t)(this.x + this.y);
> >     
> >     }
> 
> Yes, it's already trusted.
> 
> If I write "@trusted const pure nothrow" it works fine, but if i
> write "const pure nothrow" not. Why? I thought the compiler is
> orientating at the base method which is overriden.

Apparently, when you override an @trusted method, the method in the derived 
class is inferred to be @safe - which makes sense when you think about it, 
since the derived class' function hasn't done anything @system. If it calls 
the base class' version, which is @trusted, then it can be @safe. So, as long 
as it doesn't do anything @system itself, it can be @safe. However, since the 
compiler doesn't infer any attributes from the derived class' function's body 
(since it's not templated), if you do any @system stuff in there, it'll give 
you a compilation error rather than treating it as @system - though that makes 
sense too, since having a derived class function with worse guarantees than a 
base class function isn't valid. So, even if the attributes _were_ inferred 
from the function's body, it would _still_ have to give you an error, since 
the body would be @system when it needed to be at least @trusted.

http://d.puremagic.com/issues/show_bug.cgi?id=8275

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list