繁体   English   中英

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

[英]std::map::const_iterator template compilation error

我有一个模板类,其中包含一个std::map ,它存储指向T的指针,而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返回到地图?

使用typename

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

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

此类依赖名称 (取决于模板参数)假定为

  • 没有类型,除非前缀typename
  • 除非是template的直接前缀,否则不要成为template

您需要输入typename

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

你需要:

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

暂无
暂无

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

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