How does one use toString() inside of the class's hash function? Compiler error

Paul Backus snarwin at gmail.com
Tue Apr 1 14:09:58 UTC 2025


On Tuesday, 1 April 2025 at 09:21:25 UTC, Daniel Donnelly, Jr. 
wrote:
> Something like this.  I know I could very well hash latex 
> member, but what if the user redefines toString() ?  So I would 
> like to call toString(), but DMD compiler bitches:
>
> ```
> Error: @safe function def.Def.toHash cannot call @system 
> function def.Def.toString: def.Def.toString is declared here...
> ```

This works for me:

```d
    @safe nothrow override string toString() const
    {
       return latex;
    }

    override nothrow @safe size_t toHash()
    {
       auto s = toString();
       return hashOf(s);
    }
```

Changes made:

* Mark `toString` as `@safe` and `nothrow`.
* Use [`hashOf`][1] instead of `getHash`.

[1]: https://dlang.org/phobos/object.html#.hashOf


More information about the Digitalmars-d-learn mailing list