0

When I use the template as below, the g++ will report error:


E32.cpp: In function ‘void display_vector(const std::vector&, std::ostream&, int)’:

E32.cpp:21:5: error: need ‘typename’ before ‘std::vector::const_iterator’ because ‘std::vector’ is a dependent scope vector::const_iterator ^


template <typename elemType>                                                
void display_vector(const vector<elemType> &vec,
            ostream &os=cout, int len=8)
{
    vector<elemType>::const_iterator
        iter = vec.begin(),
        end_it = vec.end();
    int elem_cnt = 1;
    while(iter != end_it)
    {
        os << *iter++ << (!(elem_cnt++ % len)?'\n':' ');
    }
    os << endl;
}

Why? I can't figure it out...

Joe
  • 381
  • 2
  • 6
  • 13

1 Answers1

1

Use typename here:

typename vector<elemType>::const_iterator

Because const_iterator is a dependent name (which is also shown in the error message). Search this site to know more about dependent-name.

Better use auto and range-based for loop.

Nawaz
  • 353,942
  • 115
  • 666
  • 851