http://blog.163.com/kingrogo@yeah/blog/static/17020105120104185466354/
STL中使用模板 2010-05-18 17:46:06| 分类: 喜羊羊|字号 订阅#include <vector>#include <cstdlib>
代码:
using namespace std;
template < typename T >
T min( const vector<T> &vec )
{
if ( !vec.size() )
exit( 1 );
vector<T>::const_iterator iter = vec.begin(); //这句怎么都编译不过去
T min = *iter;
for( ++iter; iter!=vec.end(); ++iter)
if( *iter<min )
min = *iter;
return min;
}
(只考虑语法)
总是提示expected `;' before "iter"
我把那句vector<T>::const_iterator中的<T>临时换成vector<int>其他什么都不改就没错误;
把这段移到VC上编也没有语法错误,但是在GCC中编译错误
解释:(没肿么看懂)
What happens here? The offensive expression is "vector <T>::const_iterator". Now std::vector is a class template and one important characteristic of those templates is, that you can specialize them for different types or type families. Therefore the compiler cannot know in this generic context, whether "vector <T>::const_iterator" describes a type or not. In this case the standard requires the compiler to assume that vector <T>::const_iterator is a non-type (it could be a number, for example). After instantiation with a concrete T happened, the compiler found out that vector <T>::const_iterator indeed *was* a type. Therefore it's reasoning
错误信息
"'std::vector <T,std::allocator <_CharT> >::const_iterator' is parsed as a non-type, but instantiation yields a type" is very true. Fortunatly the standard allows you to describe "vector <T>::const_iterator" as a type and the only thing you need to do is to prefix it with the keyword "typename" like this: