Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "Template Constructors" in D?

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"?

like image 632
dprogramminglanguagedisposable Avatar asked Jul 01 '11 22:07

dprogramminglanguagedisposable


1 Answers

I asked around on IRC, and as far as we can figure out it was never implemented for D1, so we're guessing it's still unimplemented. Furthermore, there is no mention of the feature in The D Programming Language, so the whole thing is up in the air a bit.

If I were you, I would submit a bug against the documentation.

like image 113
Bernard Avatar answered Oct 10 '22 21:10

Bernard