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

Rob*_*Rob 1 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;
};
Run Code Online (Sandbox Code Playgroud)

gcc给我以下错误:

error: type 'std::map<int, T*, std::less<int>, std::allocator<std::pair<const int, T*> > >' is not derived from type 'Foo<T>'
Run Code Online (Sandbox Code Playgroud)

同样,以下内容也拒绝编译:

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;
};
Run Code Online (Sandbox Code Playgroud)

我认为这与模板有关并且引发了一个问题 - 如何将一个返回const_iterator到我的地图?

Geo*_*che 12

用途typename:

typename std::map<int, T*>::const_iterator begin() const ...
Run Code Online (Sandbox Code Playgroud)

当编译器首次传递它时,它不知道是什么T.因此,它也不知道const_iterator其实是一种类型.

假设这样的依赖名称(取决于模板参数)

  • 除非有前缀,否则不是类型 typename
  • 除非直接加上前缀,否则不要成为模板template.