在编译器中无法识别的模板函数中映射迭代器

Eli*_*Eli 4 c++ templates iterator map

我有以下代码.

template<class key,class val>
bool has_key(key chkey,std::map<key,val> map){
  for (std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc
      it!=map.end(); ++it){
    if(chkey == it->first) return true;
  }
  return false;
}
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会给我以下错误.

objects.hpp: In function `bool has_key(key, std::map<key, val, std::less<_Key>,
  std::allocator<std::pair<const _Key, _Tp> > >)':
objects.hpp:13: error: expected `;' before "it"
objects.hpp:14: error: `it' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

某种方式"它"没有被初始化,山姆海恩在这里发生了什么?!

CB *_*ley 23

你需要typename关键字:

for (typename std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc
  it!=map.end(); ++it){
Run Code Online (Sandbox Code Playgroud)

另请参阅:为什么我们需要typename?

这是因为您在模板定义中并且iterator是从属名称.以前曾经问过这个问题.

g ++"不是类型"错误

C++模板:'不是从类型'派生的'

模板中依赖类型的问题