可能重复:
Where and why do I have to put the “template” and “typename” keywords?这个静态模板函数的实现有什么问题?
我学习的模板功能。我试图实现一个清除指针列表的静态模板函数。要做到这一点,我想使用模板。其我的代码:
#include <cstdio>
#include <list>
using namespace std;
class util
{
public:
template <class ARG>
static void CleanPointers(list<ARG> &mylist) {
list<ARG>::iterator it;
for (it = mylist.begin(); it != mylist.end(); it++)
{
ARG obj = (ARG) *it;
delete obj;
}
mylist.clear();
};
util();
~util();
};
int main()
{
list<int*> mylist;
mylist.push_back(new int(1));
mylist.push_back(new int(2));
util::CleanPointers<int*>(mylist);
return 0;
}
我recived跟随编译错误消息,我不明白这里的重点。 :)为什么需要我放;在之前呢?
prog.cpp: In static member function ‘static void util::CleanPointers(std::list<ARG, std::allocator<_Tp1> >&)’:
prog.cpp:10: error: expected `;' before ‘it’
prog.cpp:11: error: ‘it’ was not declared in this scope
prog.cpp: In static member function ‘static void util::CleanPointers(std::list<ARG, std::allocator<_Tp1> >&) [with ARG = int*]’:
prog.cpp:28: instantiated from here
prog.cpp:10: error: dependent-name ‘std::list::iterator’ is parsed as a non-type, but instantiation yields a type
prog.cpp:10: note: say ‘typename std::list::iterator’ if a type is meant
我认为使用短语“清除指针”是一个非常糟糕的主意,因为这意味着什么也没有,并且可能是灾难性的误导。正确的概念是“删除一个动态分配的对象(通过调用指向该对象的指针delete”)。 –
@KerrekSB,yeap!你是对的。我会改变这一点。 –