Click here to Skip to main content
12,627,681 members (33,345 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++
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 31-Jan-13 12:38pm
tcnm326
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
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
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
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Try
...
auto ci = v.begin();
...
Cheers
Andi
  Permalink  

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


Advertise | Privacy | Mobile
Web02 | 2.8.161205.3 | Last Updated 1 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100