5

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?!

Eli
  • 2,041
  • 4
  • 18
  • 20
  • Duplicates include: http://stackoverflow.com/questions/1301380/g-is-not-a-type-error http://stackoverflow.com/questions/2841757/c-template-is-not-derived-from-type http://stackoverflow.com/questions/2931345/c-trouble-with-dependent-types-in-templates – CB Bailey Jul 06 '10 at 08:47
  • 1
    Sidenote: Are you sure you want to pass your map by value instead of const reference and use const_iterator? – pmr Jul 06 '10 at 09:46
  • pmr, thanks for the suggestion. const use is a practice I havn't gotten into yet and need to develop habits around. – Eli Jul 07 '10 at 01:00

1 Answers1

30

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

Community
  • 1
  • 1
CB Bailey
  • 755,051
  • 104
  • 632
  • 656