std :: map :: const_iterator模板编译错误 [英] std::map::const_iterator template compilation error
问题描述
我有一个包含 std :: map
的模板类,它存储指向T的指针,它拒绝编译:
template< class T>
class Foo
{
public:
//下面一行不会编译
std :: map< int,T *> :: const_iterator begin )const {return items.begin(); }
private:
std :: map< int,T *>项目;
};
gcc给我以下错误:
错误:type'std :: map< int,T *,std :: less< int> ;, std :: allocator< std :: pair< const int,T * > >'不是从类型'Foo< T>派生的
编译:
typedef std :: map< int,T *> :: const_iterator ItemIterator;
但是,使用不包含模板类型的地图可以正常工作,例如:
template< class T>
class Foo
{
public:
//这是OK
std :: map< int,std :: string> :: const_iterator begin return items.begin(); }
private:
std :: map< int,std :: string>项目;
};
我假设这与模板相关,并提出了问题 - 如何返回<$ c $ c $ c>:
typename std :: map< int,T *> :: const_iterator begin 。
当编译器第一次通过时,它不知道 T
是。因此,它也不知道 const_iterator
实际上是一个类型或不是。
这样的依赖名称(取决于模板参数)假设为
- 不是类型,除非前缀为
typename c>
- 不要是模板。 / ul>
I have a template class that contains a
std::map
that stores pointers to T which refuses to compile: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:
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, e.g.:
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?解决方案Use
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. Thus, it also doesn't know wetherconst_iterator
is actually a type or not.Such dependent names (dependent on a template parameter) are assumed to
- not be types unless prefixed by
typename
- not to be templates unless directly prefixed by
template
.
这篇关于std :: map :: const_iterator模板编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- not be types unless prefixed by