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是一个模板结构的语法相同,这是非常合理的。
那么,有人知道如何声明和调用“模板构造函数”吗?