【发布时间】:2012-06-10 15:58:27
【问题描述】:
为什么我不能重载这个模板函数?
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;
}
据我所知,这两个函数不能接受相同的参数类型。
【问题讨论】:
-
我认为该语言不允许您重载 any 模板函数..
-
@Mehrdad:你可以超载。特别是 std.algorithm.find 被多次重载。
-
@PeterAlexander:真的等一下?每次我尝试将常规函数“重载”为模板函数时,都会出现错误....
-
@Mehrdad:啊,是的,你不能用非模板函数重载模板函数,但我认为这是一个 DMD 错误。不确定。
-
我在阅读 TDPL 的第 5 章时编写了这段代码,这清楚地表明您可以使用
int[] find(int[] longer, int[] shorter)重载 find() 模板,并且如果参数与普通函数兼容,编译器应该即使模板函数也可以接受参数,也要使用普通函数。
标签: templates overloading d