This question already has answers here:
Where and why do I have to put the “template” and “typename” keywords?
                                
                                    (6个答案)
                                
                        
                                去年关闭。
            
                    
我试图创建一个模板函数,该函数接收指向类T的某些指针的向量并清除该向量。但是,使用下面的实现,我得到编译错误。我究竟做错了什么?

template <class T>
void clearVectorOfPointers(vector<T>& v){
for (vector<T>::iterator it = v.begin(); it != v.end(); ++it){
    delete (*it);
}

v.clear();
}

symbolTable.cpp: In function ‘void clearVectorOfPointers(std::vector<T, std::allocator<_CharT> >&)’:
symbolTable.cpp:8: error: expected ‘;’ before ‘it’
symbolTable.cpp:8: error: ‘it’ was not declared in this scope

最佳答案

您应该使用typename关键字访问typedef iterator

template <class T>
void clearVectorOfPointers(vector<T>& v){
for (typename vector<T>::iterator it = v.begin(); it != v.end(); ++it)
{
    delete (*it);
}

v.clear();
}


因为您使用dependent name

关于c++ - 清除指针 vector 的模板函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53653313/

10-11 22:42
查看更多