2011-12-14 52 views
2

我一直在試圖做Ex。 10-02加速C++,它給我錯誤,我最終保持「簡化」我的程序,直到我到了這一點,甚至仍然不會編譯(通過g ++)給我的錯誤:帶迭代器的模板函數

test.cpp: In function ‘int main()’: 
test.cpp:22: error: no matching function for call to ‘dumb(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >)’ 

這是我的計劃:

#include <algorithm> 
#include <iostream> 
#include <vector> 

using std::cout; using std::endl; 
using std::vector; 

template <class Ran, class T> T dumb(Ran begin, Ran end) 
{ 
    return *begin; 
} 

int main() 
{ 
    vector<int> myVector; 
    for (int i = 1; i <= 9; ++i) 
     myVector.push_back(i); 

    int d = dumb(myVector.begin(), myVector.end()); 
    cout << "Value = " << d << endl; 
    return 0; 
} 

是什麼造成這個錯誤?

回答

5

編譯器無法在此處推斷返回類型。實際上,沒有必要在這裏製作返回類型的模板參數:

template <class Ran> typename Ran::value_type dumb(Ran begin, Ran end) 
{ 
    return *begin; 
} 
+0

+1擊敗我吧,grump ... – hmjd

+0

+1,這個答案更簡單,正確的方式來處理這樣的容器。 – iammilind

+0

啊,很好..我的書還沒有涵蓋:: value_type的用法,雖然我看了索引,它在下一章..雖然很好的乾淨的方式來解決我的問題,謝謝! – adelbertc

1

的問題是你的函數原型:

template <class Ran, class T> T dumb(Ran begin, Ran end) 

當使用template S,它依賴型(這裏T)返回類型,不能隱推斷。

所以你重新設計的功能應該是這樣的:

template <class T, class Ran> 
      // ^^^^^ 'T' is coming before 'Ran' 
T dumb(Ran begin, Ran end) 
{ 
    return *begin; 
} 

,它應該被稱爲,

int d = dumb<int>(myVector.begin(), myVector.end()); 
      ^^^^ 

因此,我們已經做了2個變化:

  1. 的必須明確提及的類型(即T=int)是 即將到來的第一個
  2. 調用dumb<>int明確提及,所以 返回類型推斷出

[注:本解決方案的理解非常通用。正如@Bjorn的回答中所提到的,對於vector<>,可以使用::value_type自動推斷出該類型。]

+0

謝謝!我的書在調用模板函數時確實包含了明確提及的用法,忘記了這一點。不像@比約恩那樣乾淨,但是與我迄今爲止所應具備的知識一起工作。 +1 – adelbertc