【问题标题】:Nested struct in templated class with std::map::const_iterator?带有std :: map :: const_iterator的模板类中的嵌套结构?
【发布时间】:2009-03-19 08:54:23
【问题描述】:

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

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 中移出,代码编译得很好。

【问题讨论】:

    标签: c++ templates nested stdmap


    【解决方案1】:

    你需要一个类型名:

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

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

    here的问题进行了合理的讨论。

    【讨论】:

    • +1。我可以建议在“当您遇到这种情况时”之后添加“在模板定义中”的字样吗?
    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多