1

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
map iterator in template function unrecognized by compiler

I have a template function which has std::map::iterator instantiation within it -

template <class B , class C> 
C getValue (B& myMap , C returnType) {
    map<string,C>::iterator it = myMap.find(var);
    // implementation ...
}

and it prompt errors -

In function ‘C getValue(char*, B&, C)’:
error: expected ‘;’ before ‘it’
error: ‘it’ was not declared in this scope

How should I have make it properly ?

Community
  • 1
  • 1
URL87
  • 10,667
  • 35
  • 107
  • 174
  • 1
    You can use `auto it = myMap.find(var);`. –  Dec 06 '12 at 12:23
  • @Zoidberg'-- : what is this auto ? can your give more details please ? – URL87 Dec 06 '12 at 12:26
  • @URL87: using `auto` like that is a recent addition to the language. It declares the variable to have the same type as its initialiser. It's very useful in cases like this where the type can be awkward (or even impossible) to write. – Mike Seymour Dec 06 '12 at 12:33

1 Answers1

3

It is a dependent type so you need typename:

typename map<string,C>::iterator it = myMap.find(var);

See Where and why do I have to put the "template" and "typename" keywords? for much more detail.

As commented by Zoidberg', C++11 has auto which instructs the compiler to deduce the type. See Elements of Modern C++ Style for a brief overview (with some other features).

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252