gpt4 book ai didi

templates - 为什么我不能使用同名技巧链接实例化?

转载 作者:行者123 更新时间:2023-12-02 03:37:29 26 4
gpt4 key购买 nike

在D中,当模板有一个与模板同名的成员时,模板的任何实例化都直接引用该成员。但是如果那个成员本身就是一个模板,出于某种原因我不能立即实例化它。但是,创建一个中间别名是可行的。

template Foo(int x){
template Foo(int y){
enum int Foo = x+y;
}
}
alias Foo1 = Foo!(1);
assert(Foo1!(2) == 3); // ok
int a = Foo!(1)!(1); // compile error Error: found '!' when expecting ')'

为什么会失败?有什么办法解决这个问题吗?

我的目标是整洁和柯里化(Currying)。

最佳答案

D 语法就是这样定义的。当前编译器显示正确的错误消息:

Error: multiple ! arguments are not allowed

此外,此问题已提交为 Issue 1566来自issue comment 4 :

If I don't miss something multiple ! is considered harmful as A!B!C may be considered as A instantiated with B!C or A!B instantiated with C. Also requirement to always have parantheses in such case may be added but IMO it doesn't look like a worthwhile language complication as it isn't generally needed.

这可以通过例如这样的 Inst 模板:

template Foo(int x)
{ enum int Foo(int y) = x + y; }

alias Inst(alias Template, A...) = Template!A;

enum a = Inst!(Foo!1, 1);

注意 D 现在有一个新的简短模板声明语法,并且在模板参数是标识符或常量的情况下也不需要使用括号。

关于templates - 为什么我不能使用同名技巧链接实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22460321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com