注册 登录
编程论坛 C++教室

[求助]模版函数出问题了!

aipb2007 发布于 2007-06-10 16:23, 1348 次点击
template<class T>
vector<T>::iterator find(vector<T>::iterator fir,vector<T>::iterator sec,
const T &key){
for (;fir != sec;++fir){
if (*fir == key)
return fir;
}
return sec;
}
定义了个模板函数查找vector中的元素,我想返回vector的迭代器。
编译出错,提示,参数类型嵌套依靠类型。

那我该怎么改?

奇怪的是在vc++6.0下能通过,连警告都没有!
12 回复
#2
wfpb2007-06-10 16:30

这样修改下看看行不行.
template<class T>
typename vector<T>::iterator find(typename vector<T>::iterator fir,typename vector<T>::iterator sec,
const T &key){
for (;fir != sec;++fir){
if (*fir == key)
return fir;
}
return sec;
}

#3
aipb20072007-06-10 16:59
回复:(wfpb)这样修改下看看行不行.template

还是不行!

#4
wfpb2007-06-11 02:49
你用的什么编译器啊,vs2005加了typename后可以啊。。。
#5
aipb20072007-06-11 09:25
我用的vc++2005啊,我再试试嘛!
#6
aipb20072007-06-11 09:27
回复:(aipb2007)[求助]模版函数出问题了!

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template<class T>
typename vector<T>::iterator find(vector<T>::iterator fir,vector<T>::iterator sec,
const T &key){
for (;fir != sec;++fir){
if (*fir == key)
return fir;
}
return sec;
}

int main(){
vector<int> ivec;
int temp;
while (cin >> temp)
ivec.push_back(temp);
vector<int>::iterator p = find(ivec.begin(),ivec.end(),100);
cout << *p << endl;
system("pause");
return 0;
}

f:\practise for vc++2005\practise\practise\prac.cpp(7) : warning C4346: 'std::vector<T>::iterator' : dependent name is not a type
prefix with 'typename' to indicate a type
f:\practise for vc++2005\practise\practise\prac.cpp(7) : error C2146: syntax error : missing ')' before identifier 'fir'
f:\practise for vc++2005\practise\practise\prac.cpp(8) : error C2059: syntax error : ')'
f:\practise for vc++2005\practise\practise\prac.cpp(16) : error C2143: syntax error : missing ';' before '{'
f:\practise for vc++2005\practise\practise\prac.cpp(16) : error C2447: '{' : missing function header (old-style formal list?)
Build log was saved at "file://f:\practise for vc++2005\practise\practise\Debug\BuildLog.htm"
practise - 4 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
#7
wfpb2007-06-12 09:18
我晕,参数里面也要加啊。。。
#8
aipb20072007-06-12 09:30
回复:(aipb2007)[求助]模版函数出问题了!


怎么加了就行了啊,给我讲下好不?
#9
wfpb2007-06-12 10:02
我也是看了typename与class的区别才知道的,你可以用baidu搜搜看,比我讲的清楚。
#10
wfpb2007-06-12 10:03
不加typename编译器会以为是A::s是类的静态成员,而不认为是类型。。。
#11
yuyunliuhen2007-06-12 10:26

mark...

#12
aipb20072007-06-12 10:59
回复:(wfpb)不加typename编译器会以为是A::s是类的...
这个我知道了,去帮我看下这个
https://bbs.bc-cn.net/viewthread.php?tid=146735

谢了!
#13
aipb20072007-06-12 11:00
回复:(yuyunliuhen)mark...[em01]
不要mark了,去给我看看,被模板搞的头都大了!

呵呵~~
1