How to use "Template Constructors" in D?
Asked Answered
L

1

11

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

Limon answered 1/7, 2011 at 22:54 Comment(0)
G
7

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.

Godroon answered 2/7, 2011 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.