2015-08-15 64 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

相關問題