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 fol开发者_C百科lowing 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?
typename std::vector<T>::size_type i;
http://womble.decadent.org.uk/c++/template-faq.html#disambiguation
size_type is a dependent name, you need to prefix it with typename
, i.e.:
typename std::vector<T>::size_type i;
精彩评论