2

I have written the following template function for summing the contents of a std::vector object. It is in a file by itself called sum.cpp.

#include <vector>

template<typename T>
T sum(const std::vector<T>* objs) {
    T total;
    std::vector<T>::size_type i;
    for(i = 0; i < objs->size(); i++) {
        total += (*objs)[i];
    }
    return total;
}

When I try to compile this function, G++ spits out the following error:

sum.cpp: In function ‘T sum(const std::vector<T, std::allocator<_Tp1> >*)’:
sum.cpp:6: error: expected ‘;’ before ‘i’
sum.cpp:7: error: ‘i’ was not declared in this scope

As far as I can tell the reason that this error is returned is because std::vector<T>::size_type cannot be resolved to a type. Is my only option here to fall back to std::size_t (which if I understand correctly is often but not always the same as std::vector<T>::size_type), or is there a workaround?

Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
WirthLuce
  • 1,361
  • 13
  • 23
  • 4
    Oh no, not again :-) Seriously, this is the most common question about templates here, but irritatingly difficult to search for. –  May 11 '11 at 23:14
  • 1
    [Where and why do I have to put “template” and “typename” on dependent names?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-template-and-typename-on-dependent-names) – Xeo May 11 '11 at 23:14
  • 1
    @Xeo - of the question poster knows about "typename" and what "dependent names" are, probably will know the answer by him/herself :D – Kiril Kirov May 11 '11 at 23:30
  • @Kiril: I just posted that link as a reference. :) – Xeo May 11 '11 at 23:44
  • Thanks, I tried searching for this but I couldn't find anything. – WirthLuce May 12 '11 at 00:03
  • Im so glad you like my littl faq entry. I put so much love into it! – Johannes Schaub - litb May 12 '11 at 05:27

2 Answers2

6
typename std::vector<T>::size_type i;

http://womble.decadent.org.uk/c++/template-faq.html#disambiguation

Anycorn
  • 50,217
  • 42
  • 167
  • 261
3

size_type is a dependent name, you need to prefix it with typename, i.e.:

typename std::vector<T>::size_type i;
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274