【发布时间】:2014-10-17 21:20:24
【问题描述】:
我试图将一个迭代器从一个模板函数返回到一个向量(还不是一个模板类成员——我还在写那个)。编译器不断给我错误(复制如下以方便谷歌搜索)。我基本上知道问题出在哪里,但确切的语法难以捉摸。
我阅读了互联网,搜索了 SO,包括 Where and why do I have to put the "template" and "typename" keywords?,但没有找到有效的答案。我想我应该在这里提出问题并自己回答。
(略)原代码如下:
#include <vector>
#include <algorithm> // std::lower_bound
template<typename T> std::vector<T>::iterator
insertIntoVector(std::vector<T>& vec, const T& val)
{ itr = [some std::vector<T> iterator];
return itr; // return iterator to val in vec.
} // End of insertIntoVector();
编译器错误:
error C2145: syntax error: missing ';' before identifier 'insertIntoVector'
error C2065: 'T' : undeclared identifier
error C2923: 'std::vector' : 'T' is not a valid template type argument for parameter '_Ty'
明智地,我尝试了这个:
template<typename T> typename std::vector<T>::iterator
insertIntoVector(std::vector<T>& vec, const T& val)
更多编译器错误:
error C1075: end of file found before the left brace '{'
如果这个问题被解锁,我会在下面发布我的答案。否则,请在Where and why do I have to put the "template" and "typename" keywords? 上查看我的回答。
【问题讨论】:
-
使用
template<typename T> typename std::vector<T>::iterator,因为你有一个依赖类型 -
我不同意这个问题是重复的。首先,我在 SO 上搜索了我的 *ss off 以寻找答案。我怎么知道要搜索的神奇问题?问题是关于一个模板函数的返回类型,它返回一个迭代器到一个stl容器。这些关键字不会将我引向所引用的问题。
-
@vsoftco。 typename std::vector
::iterator 也不起作用,尽管依赖类型问题在正确的轨道上。当我因重复问题而被锁定时,我正在发布我的答案。阅读引用的问题,看看你是否发现你的建议有什么问题,或者即使它解决了返回类型。 -
@T.C.我再次查看了您引用的问题,使用浏览器搜索功能查找“返回类型”。那里甚至没有返回这个词。 vsoftco 上面的评论也不完全正确。显然你的引用并没有解决我的(前)问题。我本想尽自己的一份力,回馈社区,但在花了半个小时写完我的答案后,你把我赶走了。不确定我想再试一次。
-
@riderBill 依赖类型问题非常频繁地出现,这就是为什么我们中的一些人将这些问题作为规范问题的重复而关闭。那些搜索仍然可以找到将它们指向规范问题和答案的重复项。如果您能解释您的答案将涵盖哪些额外基础,我很乐意重新投票,因为据我所知,您发布的编译器错误都是由缺少
typename引起的。
标签: c++ stl iterator return-type template-function