【发布时间】:2012-09-13 14:30:36
【问题描述】:
可能重复:
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;
}
我收到了以下编译错误消息,但我不明白这里有什么意义。 :) 为什么需要我放;之前?
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,是的!你说的对。我会改变的。