为什么 GCC 不允许我将模板参数用于另一个模板的参数?

Why won't GCC let me use a template parameter for another template's parameter?

本文关键字:参数 另一个 用于 GCC 为什么 不允许 允许我      更新时间:2023-10-16

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

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

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

size_type是一个

依赖名称,你需要用typename前缀,即:

typename std::vector<T>::size_type i;
相关文章: