Jos*_*ver 15 c++ templates typename c++-standard-library
我正在尝试使用C++标准库的find算法,如下所示:
template<class T>
const unsigned int AdjacencyList<T>::_index_for_node(
const std::vector<T>& list, const T& node
) throw(NoSuchNodeException)
{
std::vector<T>::iterator iter = std::find(list.begin(), list.end(), node);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译时,我得到以下错误:
In file included from ../AdjacencyList.cpp:8:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
In file included from ../AdjacencyListTest.cpp:9:
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
../AdjacencyList.h:99: error: expected ‘;’ before ‘iter’
../AdjacencyList.h:100: error: ‘iter’ was not declared in this scope
../AdjacencyList.h: In member function ‘const unsigned int Graph::AdjacencyList<T>::_index_for_node(const std::vector<T, std::allocator<_Tp1> >&, const T&) [with T = int]’:
../AdjacencyList.h:91: instantiated from ‘const std::vector<T, std::allocator<_Tp1> > Graph::AdjacencyList<T>::neighbours(const T&) [with T = int]’
../AdjacencyListTest.cpp:18: instantiated from here
../AdjacencyList.h:99: error: dependent-name ‘std::vector::iterator’ is parsed as a non-type, but instantiation yields a type
../AdjacencyList.h:99: note: say ‘typename std::vector::iterator’ if a type is meant
Run Code Online (Sandbox Code Playgroud)
我觉得"依赖名称'std :: vector :: iterator'被解析为非类型,但是实例化产生了一种类型"bit是理解我做错了什么的关键,但我的豌豆脑不能提取意义.
更新:我需要typename根据接受的答案添加一个,并且还使用a const_iterator,因此有问题的代码行变为:
typename std::vector<T>::const_iterator iter = std::find(list.begin(), list.end(), node);
Run Code Online (Sandbox Code Playgroud)
Jam*_*lis 35
std::vector<T>::iterator iter = /* .... */;
Run Code Online (Sandbox Code Playgroud)
iterator是一个从属名称(实际上,它取决于类型参数T).除非您使用typename以下内容,否则假定从属名称不是名称类型:
typename std::vector<T>::iterator iter = /* .... */;
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Stack Overflow C++ FAQ条目"在哪里以及为什么必须在依赖名称上放置"template"和"typename"?
您还需要使用const_iterator,因为list是const限定的.您也应该删除异常规范; 最好"永远不要编写异常规范".