返回不同输入范围时的函数返回类型不匹配现象

时间:2015-08-15 10:13:33

标签: templates d

当我从同一个函数中返回不同类型的InputRanges时,我收到此错误:Error: mismatched function return type inference oftaketakeExactly返回的类型由于某种原因与原始输入范围兼容,但与我的自定义输入范围不兼容。

auto decode(Range)(Range r) {
  if (r.front == 0) {        
    r.popFront();
    return r;
  } else if (r.front == 1) {
    r.popFront();
    return r.take(3); // this is compatible with the return type above
  } else if (r.front == 2) {
    r.popFront();
    return MyRange(r); // this is not compatible with the types above
  }
}

发生了什么事?

1 个答案:

答案 0 :(得分:3)

template Take(R)不会改变您从编译器获得的消息错误。问题是返回类型在仅在运行时有效的函数中有所不同。

不同的返回类型只能在编译时推断,但在这种情况下,r.front值不可知。

这里简化一个例子,摆脱范围并重现问题

// t can be tested at compile-time, fun is a template
auto fun(int t)()
{
    static if (t == 0) return "can be inferred";
    else return new Object; 
}

// t cant be tested at compile-time and this produces your error:
// Error: mismatched function return type inference of typethis and that 
auto notfun(int t)
{
    if (t == 0) return "cant be inferred";
    else return new Object; 
}

void main(string[] args)
{
    import std.stdio;
    fun!0().writeln; // works, returns a string
    fun!1().writeln; // works, returns an int
}

最后你有两个选择:

  • 找到一个普通类型
  • 从函数中测试r.front并根据值调用不同的重载。