templates - 如何在 D 中使用 "Template Constructors"?

标签 templates d compile-time dmd

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 是模板结构相同。

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

最佳答案

我在 IRC 上四处询问,据我们所知,它从未在 D1 中实现过,所以我们猜测它仍然没有实现。此外,The D Programming Language 中没有提到该功能,所以整个事情有点悬而未决。

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

关于templates - 如何在 D 中使用 "Template Constructors"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6553950/

相关文章:

c++ - 模板类中私有(private)weak_ptr的定义

c++ - 忽略函数默认参数

struct - 使用单个引用传递结构是否有任何隐藏成本?

c - 如何在 D 中创建可以与 C 代码接口(interface)的连续多维数组?

c++ - sizeof(值)与 sizeof(类型)?

c++ - Constexpr 排序的唯一容器集作为数组包装器

c++ - 将可变参数模板参数包传递给下一个函数

android - 类似Android的CSS/HTML网站模板?

functional-programming - 使用种子减少字符串数组

ios - iOS ARM 代码可以在模拟器中运行吗?