STL中使用模板在gcc中无法通过编译

3 篇文章 0 订阅
2 篇文章 0 订阅

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: 


解决:

typename vector <T>::const_iterator itValues = v_values.begin(); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值