我有一个模板类,其中包含一个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其实是一种类型.
假设这样的依赖名称(取决于模板参数)
typenametemplate.