【问题标题】:How to use "Template Constructors" in D?如何在 D 中使用“模板构造函数”?
【发布时间】:2011-07-01 22:54:24
【问题描述】:

template documentation for 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 是模板结构一样,这非常合乎逻辑。

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

【问题讨论】:

    标签: templates d compile-time dmd


    【解决方案1】:

    我在 IRC 上四处询问,据我们所知,它从未为 D1 实现过,所以我们猜测它仍未实现。此外,D 编程语言中没有提及该功能,所以整个事情都悬而未决。

    如果我是你,我会 submit a bug 反对文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 2017-09-12
      • 1970-01-01
      • 2018-10-21
      • 2019-10-08
      • 2011-05-24
      • 2017-07-10
      相关资源
      最近更新 更多