未能在模板化函数/类中使用 stl 容器
当我尝试编译以下代码时...
#include <vector>
template <class T> void DoNothing()
{
std::vector<T>::iterator it;
}
int main(int argc, char**argv)
{
return 0;
}
g++ 说:
test.cpp:5: 错误:预期为“;” 前 “它”
我不明白为什么这是一个问题。 如果我用 std::vector
替换它,那么它会按预期正常工作。
正如你所看到的,我没有实例化该函数,因此 g++ 模板定义本身一定有问题,但我看不出它是如何无效的。
感谢您对正在发生的事情提出任何建议。
注意,我实际上正在尝试编写一个模板类,并且遇到了地图而不是向量的问题,但这是我的问题的最简单的测试用例。
When I try and compile the following code...
#include <vector>
template <class T> void DoNothing()
{
std::vector<T>::iterator it;
}
int main(int argc, char**argv)
{
return 0;
}
g++ says:
test.cpp:5: error: expected `;' before
‘it’
And I don't understand why this is a problem. If I replace it with std::vector<int>::iterator
, say, it works fine as expected.
As you can see i'm not instantiating the function, so g++ must have a problem with the template definition itself, but I can't see how its invalid.
Thanks for any advice about whats going on.
NB I'm actually trying to write a templated class and having issues with a map rather than a vector, but this is the simplest test case for my problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用
typename
关键字,因为std::vector::iterator
类型依赖于模板参数:当您需要时,它实际上可能会令人困惑当你不需要它(或者甚至不被允许使用它)时使用
typename
。 这篇文章有一个不错的概述:You need to use the
typename
keyword because thestd::vector<T>::iterator
type is dependent on the template parameter:It can actually be confusing when you need to use
typename
and when you don't need it (or are even not permitted to use it). This article has a decent overview:我同意这很令人困惑。 如果没有
typename
关键字,该名称将被视为静态成员。 Vandevoorde 和 Josuttis 所著的《C++ 模板》一书详细解释了这一点。I agree it is confusing. Without the
typename
keyword, the name would be considered a static member. The book C++ Templates by Vandevoorde and Josuttis explains this in detail.typename std::vector::iterator it; 是否有效?
编辑:将
template
更改为typename
...让我的关键字混淆了。Does
typename std::vector<T>::iterator it;
work?EDIT: change
template
totypename
... got my keywords mixed up.