为什么 GCC 不允许我使用一个模板参数作为另一个模板的参数?
我编写了以下模板函数来对 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
无法解析到一个类型。我唯一的选择是回退到 std::size_t
(如果我理解正确的话,它经常,但不总是与 std::vector
),或者有解决方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://womble.decadent.org.uk/c++/template-faq .html#消歧义
http://womble.decadent.org.uk/c++/template-faq.html#disambiguation
size_type是一个依赖名称,需要在其前面加上
typename
前缀,即:size_type is a dependent name, you need to prefix it with
typename
, i.e.: