这里的冲突在哪里?

时间:2012-06-10 15:58:27

标签: templates overloading d

为什么我不能重载此模板函数?

import std.stdio;

T[] find(T, E)(T[] haystack, E needle)
    if (is(typeof(haystack[0] != needle)))
{
    while(haystack.length > 0 && haystack[0] != needle) {
        haystack = haystack[1 .. $];
    }
    return haystack;
}

// main.d(14): Error: function main.find conflicts with template main.find(T,E) if (is(typeof(haystack[0] != needle))) at main.d(5)
double[] find(double[] haystack, string needle) { return haystack; }

int main(string[] argv)
{
    double[] a = [1,2.0,3];
    writeln(find(a, 2.0));
    writeln(find(a, "2"));
    return 0;
}

据我所知,这两个函数不能接受相同的参数类型。

1 个答案:

答案 0 :(得分:9)

您不能使用非模板函数due to a bug重载模板函数。希望将来某个时候能够修复它。

在此期间,您可以将其他功能编写为模板专业化:

T find(T : double[], E : string)(T haystack, E needle)
{
    return haystack;
}