T :: Iteratorでのエラー。テンプレートパラメーターtがvector またはlist である可能性があります
質問
一般的なSTLコンテナ(ベクトル、リストなど)の表現を印刷する関数を作成しようとしています。たとえば、ベクトルを表す可能性のあるテンプレートパラメーターTを関数に与えました。タイプTのイテレーターを取得するのに問題があります。
vector<int> v(10, 0);
repr< vector<int> >(v);
...
template <typename T>
void repr(const T & v)
{
cout << "[";
if (!v.empty())
{
cout << ' ';
T::iterator i;
for (i = v.begin();
i != v.end()-1;
++i)
{
cout << *i << ", ";
}
cout << *(++i) << ' ';
}
cout << "]\n";
}
...
brett@brett-laptop:~/Desktop/stl$ g++ -Wall main.cpp
main.cpp: In function ‘void repr(const T&)’:
main.cpp:13: error: expected ‘;’ before ‘i’
main.cpp:14: error: ‘i’ was not declared in this scope
main.cpp: In function ‘void repr(const T&) [with T = std::vector<int, std::allocator<int> >]’:
main.cpp:33: instantiated from here
main.cpp:13: error: dependent-name ‘T::iterator’ is parsed as a non-type, but instantiation yields a type
main.cpp:13: note: say ‘typename T::iterator’ if a type is meant
コンパイラが提案したように、「TypeName T :: Iterator」を試しましたが、より不可解なエラーしかありませんでした。
編集:助けてくれてありがとう!この関数を使用したい人のための作業バージョンは次のとおりです。
template <typename T>
void repr(const T & v)
{
cout << "[";
if (!v.empty())
{
cout << ' ';
typename T::const_iterator i;
for (i = v.begin();
i != v.end();
++i)
{
if (i != v.begin())
{
cout << ", ";
}
cout << *i;
}
cout << ' ';
}
cout << "]\n";
}
解決
あなたが必要です typename
コンパイラにそれを伝えるために ::iterator
タイプであるはずです。コンパイラは、テンプレートをインスタンス化するまでtがわからないため、タイプであることを知りません。また、たとえば、いくつかの静的データメンバーを参照することもできます。それがあなたの最初のエラーです。
2番目のエラーはそれです v
リファレンスです -const. 。だから、ではなく ::iterator
使用する必要があります ::const_iterator
. 。非コンストイテレーターの一定の容器に尋ねることはできません。
他のヒント
変化する T::iterator i;
に typename T::const_iterator i;
なぜなら ::iterator
タイプです T
と v
aです const &
.
資格のある依存型タイプの前に、必要です typename
。それなし typename
, 、資格のある依存名を次のように解析する必要があると言うC ++解析ルールがあります non-types
構文エラーにつながる場合でも。
typename
次の名前はタイプとして扱う必要があると述べています。それ以外の場合、名前は非タイプを参照すると解釈されます。