理解 D 中的模板

Cai*_*inG 1 d template-specialization

我正在自学“D”,我有一个关于模板的问题,对某些人来说可能看起来很基本。例如,我目前正在阅读的文章(请参阅本文底部)包含以下代码:

int foo(int x)
{
    return x;
}

string foo(string x)
{
    return x;
}

void main()
{
    assert(foo(12345) == 12345);
    assert(foo("hello") == "hello");
}
Run Code Online (Sandbox Code Playgroud)

显然,这个特定的片段不够优雅,模板将消除重复:

foo(T)(T x)
{
    return x;
}

void main()
{
    assert(foo!(int)(12345) == 12345);
    assert(foo!(string)("hello") == "hello");
}
Run Code Online (Sandbox Code Playgroud)

The second example is rather basic since we are merely returning the value passed. My confusion arises by the fact that the function, however templated, still appears to be constrained to one type of value since I cannot easily envision a string and an integer value having a great deal in common. Therefore, is a programmer expected to check for the type of variable passed and then write code to handle cases of string or integer separately? Is creating a large function body truly more efficient? I realize my unfamiliarity with templating is obvious. Hence my question :)

http://nomad.so/2013/07/templates-in-d-explained/

qzn*_*znc 5

“模板”的字面定义是“作为模型供他人复制的东西”,这就是编译器所做的。对于每种类型(在您的情况下是 string 和 int),它会复制模板函数并在编译期间创建一个专门的函数。

运行时不需要模板,编译后可以扔掉。在编译后的二进制文件中有两个函数foo!(int)foo!(string).

程序员是否希望检查传递的变量类型,然后编写代码来分别处理字符串或整数的情况?

那要看。有时你想这样做。例如,优化性能。有时您不需要这样做并编写通用函数。

创建大型函数体真的更有效率吗?

有时。如果没有,那就不要做。例如,您可以编写一个通用find函数,它适用于数组、链表和类似的东西。