如何在模板化类中使用 std::map 迭代器?
我在类模板中使用私有 std::map 变量时遇到问题。谁能解释为什么以下(简化的示例)不起作用,以及我应该做什么?
#include <iostream>
#include <map>
template <class T>
class Container
{
private:
typedef std::map<long, T> Map;
typedef Map::iterator Iterator; // <-- this is line 10
Map items;
public:
void insert(const long id, const T& item) { items[id] = item; }
void print()
{
for (Iterator iter = items.begin(); iter != items.end(); iter++)
{ std::cout << iter->second << std::endl; }
}
};
int main()
{
Container<int> container;
container.insert(300, 1);
container.insert(200, 2);
container.insert(100, 3);
container.print();
return 0;
}
由此产生的错误有点神秘:
t.cpp:10: 错误:类型 'std::map, std::allocator > >'不是从类型“Container”派生的
t.cpp:10: 错误:ISO C++ 禁止声明没有类型的“迭代器”
t.cpp:10: 错误:预期为“;”在“迭代器”之前
I am having trouble using a private std::map variable from within a class template. Can anyone explain why the following (simplified example) does not work, and what I should be doing instead?
#include <iostream>
#include <map>
template <class T>
class Container
{
private:
typedef std::map<long, T> Map;
typedef Map::iterator Iterator; // <-- this is line 10
Map items;
public:
void insert(const long id, const T& item) { items[id] = item; }
void print()
{
for (Iterator iter = items.begin(); iter != items.end(); iter++)
{ std::cout << iter->second << std::endl; }
}
};
int main()
{
Container<int> container;
container.insert(300, 1);
container.insert(200, 2);
container.insert(100, 3);
container.print();
return 0;
}
The resulting error is somewhat cryptic:
t.cpp:10: error: type 'std::map, std::allocator > >' is not derived from type 'Container'
t.cpp:10: error: ISO C++ forbids declaration of 'iterator' with no type
t.cpp:10: error: expected ';' before "Iterator"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要限定依赖类型名称:
基本原理:编译器在解析模板时,无法确定是类型还是值表达式。这是因为名称取决于模板参数,而模板参数仅在实例化时才知道。
你必须帮助编译器。
旁注:
MSVC 似乎对此规则不严格,因为它的模板实例化引擎以非标准方式运行,并且无论如何,直到实例化时间才会完成名称查找
有时,依赖成员模板也需要进行限定:
You need to qualify the dependant typename:
Rationale: the compiler, at the time of parsing the template, cannot work out whether is a type or a value expression. This is because the names depend on the template argument(s), which are only known at instantiation time.
You have to help the compiler out.
Sidenotes:
MSVC seems to be lax with this rule, as it's template instantiation engine behaves in non-standard ways, and the name lookups aren't done until instantiation time anyway
sometime, dependent member templates need to be qualified as well: