我编写了以下模板函数来对 std::vector 对象的内容求和。它位于一个名为 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;
}
当我尝试编译这个函数时,G++ 吐出以下错误:
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
据我所知,返回此错误的原因是因为std::vector<T>::size_type
无法解析为类型。我在这里唯一的选择是回退std::size_t
(如果我理解正确,通常但并不总是与 相同std::vector<T>::size_type
),还是有解决方法?