有人可以解释D语言模板的简写形式吗?

Dav*_*der 14 d

我有一位教授用简写的方式为D模板写了他所有的例子:

T exec(alias f,T)(T t) {
    return f(t);
}
Run Code Online (Sandbox Code Playgroud)

我找不到任何解释这意味着什么的例子.有人可以解释一下吗?

Ada*_*ppe 16

在函数模板中,第一组parens包含模板参数,第二组包含函数参数.

http://dlang.org/template.html#function-templates

您可以将其重写为:

template exec(alias f, T) {
    T exec(T t) {
         return f(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

在使用点,如果模板成员与模板本身具有相同的名称,则不必将其写入两次.这被称为同名技巧.http://www.bing.com/search?q=eponymous+trick+d+programming+language&qs=n&form=QBRE&pq=eponymous+trick+d+programming+languag&sc=0-0&sp=-1&sk=

虽然我见过的大多数D代码都使用较短的格式 - 对于函数,类或结构来说,长模板语法非常少见,它也可以这样做:struct Foo(T){}是带有参数T的结构模板.

此exec模板中的参数本身是"别名f",它是您决定传递它的任何符号,例如,函数或变量名称,以及"T",只是任何泛型类型.重复的T是对该类型的引用.

在使用点,您很可能会看到这样的:

int foo(int a) { return a; } // just a regular function
exec!(foo)(10); // instantiates the template with arguments (foo, int), and then calls the function.
Run Code Online (Sandbox Code Playgroud)

这里的第二个模板参数由函数参数隐式计算出来.这在函数模板中非常常见:许多模板参数都是隐式的,因此您很少看到它们被写出来.您可能会在D讨论中将此引用称为"IFTI",这意味着"隐式函数模板实例化".

  • 如果您想了解有关D模板的更多信息,请访问:http://ddili.org/ders/d.en/templates.html https://github.com/PhilippeSigaud/D-templates-tutorial/blob/master/dtemplates.pdf (3认同)
  • 谢谢!有帮助! (2认同)