Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code.

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;
}

GCC is giving me the following error.

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

Somehow "it" is not being initialized, what in Sam Hain is going on here?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need the typename keyword:

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

See also: Why do we need typename here?

This is because you are in a template definition and iterator is a dependent name. This has been asked before.

g++ "is not a type" error

C++ Template: 'is not derived from type'

Trouble with dependent types in templates


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...