如何使用“模板构造函数”在D?
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 是模板结构时相同。
那么,有谁知道如何声明和调用“模板构造函数”?
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 IRC 上询问过,据我们所知,它从未在 D1 中实现过,所以我们猜测它仍未实现。此外,The D 编程语言中没有提及该功能,因此整个事情有点悬而未决。
如果我是您,我会针对文档提交错误。
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.