简体   繁体   English

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

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

I have a template class that contains a std::map that stores pointers to T which refuses to compile: 我有一个模板类,其中包含一个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 gives me the following error: gcc给我以下错误:

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

Similarly, the following also refuses to compile: 同样,以下内容也拒绝编译:

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

However, using a map that doesn't contain the template type works OK, eg: 但是,使用不包含模板类型的地图也可以,例如:

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;
};

I assume this is related to templates and begs the question - how can I return a const_iterator to my map? 我认为这与模板有关,并提出了一个问题-如何将const_iterator返回到地图?

Use typename : 使用typename

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

When this is first passed by the compiler, it doesn't know what T is. 当编译器第一次传递它时,它不知道T是什么。 Thus, it also doesn't know wether const_iterator is actually a type or not. 因此,它也不知道const_iterator是否实际上是一种类型。

Such dependent names (dependent on a template parameter) are assumed to 此类依赖名称 (取决于模板参数)假定为

  • not be types unless prefixed by typename 没有类型,除非前缀typename
  • not to be templates unless directly prefixed by template . 除非是template的直接前缀,否则不要成为template

您需要输入typename

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

You need: 你需要:

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

Or simpler 或更简单

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

This is because const_iterator is dependent name on T so you need to tell compiler that it is actually type. 这是因为const_iteratorT依赖名称,因此您需要告诉编译器它实际上是类型。

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

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