使用 std::map::const_iterator 在模板类中嵌套结构?

发布于 2024-07-15 11:42:52 字数 387 浏览 4 评论 0原文

以下代码在声明迭代器的行生成语法错误:

template <typename T>
class A
{
  public:

    struct B
    {
       int x, y, z;
    };

    void a()
    {
        std::map<int, B>::const_iterator itr; // error: ; expected before itr
    }

    std::vector<T> v;
    std::map<int, B> m;
};

仅当 A 是模板类时才会发生这种情况。 这段代码有什么问题? 如果我将 B 从 A 中移出,代码可以正常编译。

The folowing code generates a syntax error at the line where the iterator is declared:

template <typename T>
class A
{
  public:

    struct B
    {
       int x, y, z;
    };

    void a()
    {
        std::map<int, B>::const_iterator itr; // error: ; expected before itr
    }

    std::vector<T> v;
    std::map<int, B> m;
};

This only happens when A is a templated class. What's wrong with this code? If I move B out of A, the code compiles fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

眼波传意 2024-07-22 11:42:52

你需要一个类型名:

 typename std::map<int, B>::const_iterator itr;

迭代器是一个依赖类型(取决于 B),当你遇到这种情况时,编译器要求你用类型名来澄清它。

此处对该问题进行了合理的讨论。

You need a typename:

 typename std::map<int, B>::const_iterator itr;

The iterator is a dependant type (depends on B) and when you have this situation the compiler requires you to clarify it with a typename.

There is a reasonable discussion of the issue here.

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