在linux下编译模板程序出错,出错信息如下,而同样的代码在vs2003中编译通过,google了一下原来是使用vector<T>内部类型iterator时需要添加typename,加上typename后编译通过。
meta:/var/ftp/upload/test # g++ -o temp template.cpp
template.cpp: In function ‘std::string print(std::vector<Type, std::allocator<_CharT> >)’:
template.cpp:16: error: expected `;' before ‘it’
template.cpp:17: error: ‘it’ was not declared in this scope
template.cpp: In function ‘std::string print(std::vector<Type, std::allocator<_CharT> >) [with Type = int]’:
template.cpp:29: instantiated from here
template.cpp:16: error: dependent-name ‘std::vector<Type,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type
template.cpp:16: note: say ‘typename std::vector<Type,std::allocator<_CharT> >::iterator’ if a type is meant
代码如下:
//template.cpp
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
template<class Type>
string print(vector<Type> vt)
{
stringstream ss;
for(vector<Type>::iterator it = vt.begin(); it < vt.end(); it++)
{
ss << *it << " " << endl;
}
return ss.str();
}
int main()
{
vector<int> vi;
vi.push_back(100);
vi.push_back(123);
string str = print(vi);
cout << str;
return 0;
}
typename两种用法:
1。用在模板声明中,如下两个声明是一样的:
template<class T> class Widget; // uses "class"
template<typename T> class Widget; // uses "typename"
2.用于标识 nested dependent type name(嵌套依赖类型名)
浙公网安备 33010602011771号