Click here to Skip to main content
13,558,426 members
Rate this:
Please Sign up or sign in to vote.
See more:
The following simple program will not compile:
#include <map>
     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;
    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

Posted 31-Jan-13 11:38am
SAKryukov 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..?
Rate this: bad
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.
David-Serrano-Martinez 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
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

auto ci = v.begin();


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 |
Web02 | 2.8.180515.1 | Last Updated 1 Feb 2013
Copyright © CodeProject, 1999-2018
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