2015-08-15 165 views
2

我得到这个错误:当我从同一个函数中返回不同类型InputRanges的Error: mismatched function return type inference of。由taketakeExactly返回的类型由于某种原因与原始输入范围兼容,但与我的自定义输入范围不兼容。函数的返回类型不匹配的现象范围

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

'MyRange'是否有切片('opSlice')? – sigod

+0

是的,它有切片。 – Tamas

+0

实际上这就是答案:如果范围支持切片,则r和r.take(3)具有相同类型,并且它与MyRange(r)不同。谢谢!! – Tamas

回答

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出根据该值调用不同的过载。
+0

谢谢,我摆脱了问题的别名部分。这是你说的话是有道理的,但是并不能解释为什么'return r;'和'return r.take(3)'在同一个函数中工作。这是因为sigoit指出:这是一个支持切片的范围,因此它是相同的类型。 – Tamas