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

Function return type mismatch phenomenon when returning different input ranges

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

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
  }
}

怎么回事?

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

不同的 return 类型只能在编译时推断,但在这种情况下 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出函数,根据值调用不同的重载