未能在模板化函数/类中使用 stl 容器

发布于 2024-07-21 01:54:18 字数 544 浏览 2 评论 0原文

当我尝试编译以下代码时...

#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::iterator 替换它,那么它会按预期正常工作。

正如你所看到的,我没有实例化该函数,因此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萝莉病 2024-07-28 01:54:18

您需要使用 typename 关键字,因为 std::vector::iterator 类型依赖于模板参数:

template <class T> void DoNothing()
{
    typename std::vector<T>::iterator it;
}

当您需要时,它实际上可能会令人困惑当你不需要它(或者甚至不被允许使用它)时使用typename。 这篇文章有一个不错的概述:

You need to use the typename keyword because the std::vector<T>::iterator type is dependent on the template parameter:

template <class T> void DoNothing()
{
    typename std::vector<T>::iterator it;
}

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:

度的依靠╰つ 2024-07-28 01:54:18

我同意这很令人困惑。 如果没有 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.

远昼 2024-07-28 01:54:18

typename std::vector::iterator it; 是否有效?

编辑:将 template 更改为 typename ...让我的关键字混淆了。

Does typename std::vector<T>::iterator it; work?

EDIT: change template to typename ... got my keywords mixed up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文