简体   繁体   English

模板化 class 中的嵌套结构与 std::map::const_iterator?

[英]Nested struct in templated class with std::map::const_iterator?

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.这只发生在 A 是模板化的 class 时。 What's wrong with this code?这段代码有什么问题? If I move B out of A, the code compiles fine.如果我将 B 从 A 中移出,则代码编译得很好。

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.迭代器是一个依赖类型(依赖于 B),当你遇到这种情况时,编译器会要求你用类型名来澄清它。

There is a reasonable discussion of the issue here . 这里对这个问题进行了合理的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM