20

私は次のfindようなC++標準ライブラリのアルゴリズムを使用しようとしています。

  template<class T>
  const unsigned int AdjacencyList<T>::_index_for_node(
      const std::vector<T>& list, const T& node
  ) throw(NoSuchNodeException)
  {
    std::vector<T>::iterator iter = std::find(list.begin(), list.end(), node);
  }

コンパイルしようとすると、次のエラーが発生します。

In file included from ../AdjacencyList.cpp:8:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
In file included from ../AdjacencyListTest.cpp:9:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&) [with T = int]’:
../AdjacencyList.h:91:   instantiated from ‘const std::vector<T, std::allocator<_Tp1> > Graph::AdjacencyList<T>::neighbours(const T&) [with T = int]’
../AdjacencyListTest.cpp:18:   instantiated from here
../AdjacencyList.h:99: error: dependent-name ‘std::vector::iterator’ is parsed as a non-type, but instantiation yields a type
../AdjacencyList.h:99: note: say ‘typename std::vector::iterator’ if a type is meant

「dependent-name'std:: vector :: iterator'は非型として解析されますが、インスタンス化によって型が生成されるように感じます」ビットは、私が間違っていることを理解するための鍵を握っていますが、私のエンドウ豆の脳はできません意味を抽出します。

更新:typename受け入れられた回答に従って、を追加する必要があり、また、を使用する必要const_iteratorがあったため、問題のあるコード行は次のようになりました。

    typename std::vector<T>::const_iterator iter = std::find(list.begin(), list.end(), node);
4

1 に答える 1

42
std::vector<T>::iterator iter = /* .... */; 

iterator従属名です (事実上、型パラメーターに依存Tします)。以下を使用しない限り、従属名は型に名前を付けないと見なされますtypename

typename std::vector<T>::iterator iter = /* .... */;

詳細については、スタック オーバーフロー C++ の FAQ エントリ「依存する名前に「テンプレート」と「タイプ名」を配置する必要がある場所と理由は?」を読むことを検討してください。

は const 修飾されているためconst_iterator、も使用する必要があります。listおそらく、例外指定も削除する必要があります。「例外仕様は絶対に書かない」のが最善です。

于 2011-04-19T16:52:28.407 に答える