【问题标题】:Where's the conflict here?这里哪里有冲突?
【发布时间】: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


【解决方案1】:

您不能使用非模板函数due to a bug 重载模板函数。这应该有望在未来的某个时候得到解决。

与此同时,您可以将其他函数编写为模板专业化:

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

【讨论】:

  • 是的。从好的方面来说,错误正在迅速解决dlang.org/bugstats.php
  • 有时你所要做的就是添加一组空括号,ala: double[] find()(double[] haystack, string needle) { return haystack;不确定在这种情况下它是否有效,但它可以作为错误 1528 的解决方法。
猜你喜欢
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多