代码之家  ›  专栏  ›  技术社区  ›  Rob

std::map::const\迭代器模板编译错误

  •  1
  • Rob  · 技术社区  · 14 年前

    我有一个包含 std::map

    template <class T>
    class Foo
    {
    public:
      // The following line won't compile
      std::map<int, T*>::const_iterator begin() const { return items.begin(); }
    
    private:
      std::map<int, T*> items;
    };
    

    gcc给出以下错误:

    error: type 'std::map<int, T*, std::less<int>, std::allocator<std::pair<const int, T*> > >' is not derived from type 'Foo<T>'
    

    同样,以下也拒绝编译:

    typedef std::map<int, T*>::const_iterator ItemIterator;

    但是,使用不包含模板类型的映射可以正常工作,例如:

    template <class T>
    class Foo
    {
    public:
      // This is OK
      std::map<int, std::string>::const_iterator begin() const { return items.begin(); }
    
    private:
      std::map<int, std::string> items;
    };
    

    我假设这与模板有关,并回避了一个问题-如何返回 const_iterator

    3 回复  |  直到 14 年前
        1
  •  15
  •   Georg Fritzsche    14 年前

    使用 typename

    typename std::map<int, T*>::const_iterator begin() const ...
    

    当它第一次被编译器传递时,它不知道是什么 T const_iterator 是否真的是一种类型。

    这样的

    • 除非加前缀,否则不能是类型 类别名
    • 除非直接以 template
        2
  •  2
  •   Fred Larson    14 年前

    你需要 typename :

    typename std::map<int, T*>::const_iterator begin() const { return items.begin(); }
    
        3
  •  1
  •   Artyom    14 年前

    typename std::map<int, T*>::const_iterator begin() const { return items.begin(); }
    

    typedef typename std::map<int, T*>::const_iterator const_iterator;
    const_iterator begin() const { return items.begin(); }
    

    这是因为 const_iterator 依赖于名称 T