2011-12-14 11 views
2

私はExを実行しようとしています。 10-02のAccelerated 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それに私を殴る、ひどい... – hmjd

+0

+1、この答えは、そのような容器に対処するより簡単で正しい方法です。 – iammilind

+0

ああ、いいです..私の本はまだIndex_typeの使用をカバーしていませんが、私はIndexを見ていますが、次の章にあります。 – adelbertc

1

問題は、あなたの関数のプロトタイプである:(ここではT)依存の型です

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

template Sを使用して、戻り値の型、暗黙的に推定することはできません。

だからあなたの再設計された機能は次のようにする必要があります:

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. はタイプが

推論で返すので 、intを明示的に言及してdumb<>を呼び出す[注:このソリューションは、皆様のご理解のために非常に一般的です。 @ビョルンの答えで述べたように、vector<>用タイプは::value_typeを使用して自動的に推定することができる。]

+0

ありがとう!私の本は、テンプレート関数を呼び出すときに明示的に言及したことをカバーしていました。 @ Bjornのようにきれいではありませんが、これまでの知識が必要です。 +1 – adelbertc

関連する問題