2

我编写了以下模板函数来对 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),还是有解决方法?

4

2 回答 2

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

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

于 2011-05-11T23:10:58.150 回答
3

size_type 是一个依赖名称,你需要在它前面加上前缀typename,即:

typename std::vector<T>::size_type i;
于 2011-05-11T23:11:18.193 回答