代码如下:
#include<iostream> #include<string> #include<vector> #include<iterator> using namespace std;
template<class T> int find(vector<T> &vec,T data) { int index=0; vector<T>::iterator iter; for(iter=vec.begin();iter!=vec.end();iter++) { if(*iter==data) break; else index++; }
return index; }
int main() { vector<int> vec1; int i=0; for(i=0;i<10;i++) vec1.push_back(i); vector<string> vec2; vec2.push_back("zhang"); vec2.push_back("yong"); vec2.push_back("jian"); int ret; ret=find(vec1,5); if(ret==vec1.size()) cout<<"no found"<<endl; else cout<<"found,index="<<ret<<endl; ret=find(vec2,string("kang")); if(ret==vec2.size()) cout<<"no found"<<endl; else cout<<"found,index="<<ret<<endl;
return 0; }
出现的错误如下:
16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T)': 16_9.cpp:14: error: expected `;' before "iter" 16_9.cpp:15: error: `iter' was not declared in this scope 16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T) [with T = int]': 16_9.cpp:38: instantiated from here 16_9.cpp:14: error: dependent-name ` std::vector<T,std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type 16_9.cpp:14: note: say `typename std::vector<T,std::allocator<_CharT> >::iterator' if a type is meant 16_9.cpp: In function `int find(std::vector<T, std::allocator<_CharT> >&, T) [with T = std::string]': 16_9.cpp:43: instantiated from here 16_9.cpp:14: error: dependent-name ` std::vector<T,std::allocator<_CharT> >::iterator' is parsed as a non-type, but instantiation yields a type 16_9.cpp:14: note: say `typename std::vector<T,std::allocator<_CharT> >::iterator' if a type is meant
经过在Google上查询了一番,得知:
运用 vector<T>内部类型iterator时须要添加typename,加上typename后编译通过。 将上面代码中的红色部分改为下面的代码,编译没有错误。
typename vector<T>::iterator iter; typename两种用法:
1。用在模板声明中,如下两个声明是一样的:
template<class T> class Widget; // uses "class" template<typename T> class Widget; // uses "typename"
2.用于标识 nested dependent type name(嵌套依赖类型名)