如何在D语言中使用“模板构造函数”?

11

D语言的模板文档中包括一个名为“模板构造函数”的小节,但该小节没有任何示例或广泛的文档。

我正在尝试使用该功能(我知道我可以使用“静态构造函数”,但我有理由更喜欢模板构造函数)。

特别地,我正在尝试在编译时生成一些哈希值。以下是我的尝试:

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;
}

使用DMD 2.053编译无法通过:

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

它抱怨第一个构造函数。移除后:

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

考虑到我使用的语法与MyHash是一个模板结构的语法相同,这是非常合理的。

那么,有人知道如何声明和调用“模板构造函数”吗?

1个回答

7

我在IRC上询问了一下,据我们所知,它从未被实现在D1上,所以我们猜测它仍然没有被实现。此外,在《D编程语言》中也没有提到这个功能,所以整个事情有点不确定。

如果我是你,我会针对文档提交一个错误报告


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接