Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
The following simple program will not compile:
#include <map>
     2
     3 using namespace std;
     4 ^M
     5 template<class T, class A>
     6 void ShowMap(const map<T, A>& v)
     7 {
     8    map<T, A>::const_iterator ci = v.begin();
     9    return;
    10
    11 }

The compiler produces the following error message;

g++ program.cpp -o Program
2 program.cpp: In function ‘void ShowMap(const std::map<t,>&)’:
3 program.cpp:8:4: error: need ‘typename’ before ‘std::map<t,>::const_iterator’ because ‘std::map<t,>’ is a dependent scope
4 program.cpp:8:30: error: expected ‘;’ before ‘ci’
5 make: *** [Program] Error 1
~
Can anyone explain the problem to me?

Thank you very much

TCNM
Posted
Comments
Sergey Alexandrovich Kryukov 31-Jan-13 18:19pm    
Perhaps you first need to remove garbage like '^M'...
What do you want if you don't have even class brackets..?
—SA

Because of the way const_iterator is created by a typedef inside the std::map class dependent on the as yet undecided type T when your code is parsed the new C++11 standard says you need to refer to it as
typename map< T, A >::const_iterator ci = v.begin();

in other words 'the type that is named by looking up const_iterator in std::map< T, A >
templates are fun as long as you're not in a hurry.
 
Share this answer
 
v2
Comments
David Serrano Martínez 2-Feb-13 6:43am    
Leaving apart all the garbage Sergey has pointed out, I think this is the crux of the problem. const_iterator is a dependent, qualified type.
It is dependent because it depends on template parameters (T and A) and it is qualified by the presence of "::".
Without using typename, the compiler could interprete const_iterator as a static variable into map<T,A>.
tcnm 4-Feb-13 18:39pm    
Excellent solution. Thank you very much
TCNM
Try
C++
...
auto ci = v.begin();
...

Cheers
Andi
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900