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

Daniel Daniel
Tue Apr 1 09:21:25 UTC 2025


```
module def;

class Def
{
public:
    this(string latex)
    {
       this.latex = latex;
    }

    this()
    {
       this.latex = "";
    }

    override string toString() const
    {
       return latex;
    }

    string opUnary(string op="*")() const
    {
       return toString();
    }

    override bool opEquals(const Object rhs) const
    {
       return rhs is this;
    }

    override nothrow @safe size_t toHash()
    {
       auto s = toString();
       typeid(s).getHash(&s);
    }

private:
    string latex;
}

```

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...
```
I've always wondered about this, because I run into it every time 
I have an idea and begin to code.  It's a major bottleneck to my 
coding performance.

How can we fix it?



More information about the Digitalmars-d-learn mailing list