std :: map :: const_iterator模板编译错误

时间:2010-06-30 13:48:53

标签: c++ templates

我有一个模板类,其中包含一个std::map,它存储指向拒绝编译的T的指针:

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 个答案:

答案 0 :(得分:12)

使用typename

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

当编译器首次通过它时,它不知道T是什么。因此,它也不知道是否const_iterator实际上是一种类型。

这些依赖名称(取决于模板参数)被假定为

  • 除非以typename
  • 作为前缀,否则不是类型
  • 除非直接以template为前缀,否则不是模板。

答案 1 :(得分:2)

您需要typename

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

答案 2 :(得分:1)

你需要:

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_iteratorT上的依赖名称,因此您需要告诉编译器它实际上是类型。