How to use "Template Constructors" in D?

Viewed 583

The template documentation for D includes a small section called "Template Constructors". That section doesn't have any example or extensive documentation.

I'm attempting to use that feature (I'm aware that I could just use a "static constructor", but I have my reasons to prefer a template constructor).

Particularly, I'm attempting to generate some hashes at compile time. Here's my attempt:

struct MyHash
{
    uint value;

    this(uint value)
    {
        this.value = value;
    }

    this(string str)()
    {
        enum h = myHashFunc(str);
        return MyHash(h);
    }
}

uint myHashFunc(string s)
{
    // Hashing implementation
    return 0;
}

int main(string[] str)
{
    MyHash x = MyHash!"helloworld";
    return 0;
}

This doesn't compile with DMD 2.053:

x.d(10): Error: template x.MyHash.__ctor(string str) conflicts with constructor x.MyHash.this at x.d(5)

It complains about the first constructor. After removing it:

x.d(20): Error: template instance MyHash is not a template declaration, it is a struct

Which is pretty logical, considering that the syntax I use would be the same as if MyHash was a template structure.

So, does anyone know how can I declare and call a "template constructor"?

1 Answers
Related