[英]compilation error C++ templated function with iterators as arugments
I thought I was starting to get the hang of C++ .... 我以为我已经开始了解C ++了。
Then I wrote what I thought we are very simple templated function and all of a sudden it seems like nothing makes sense again. 然后我写了我以为我们是非常简单的模板化函数,突然之间似乎没有任何意义。 The compiler doesn't even seem to like the fact that I have defined a templated function, which seems a bit crazy.
编译器似乎都不喜欢我定义了模板化函数的事实,这似乎有些疯狂。 It is single unit of compilation so I am not sure what it would be complaining about.
它是单个编译单元,因此我不确定它会抱怨什么。
#include <vector>
#include <iostream>
typedef std::vector<int> int_vec_type;
template <typename Type>
bool print_vec(Type::const_iterator itr, const Type::const_iterator end)
{
for (; itr != end; ++itr) {
std::cout << *itr << std::endl;
}
return true;
}
int
main()
{
int_vec_type ivec;
ivec.push_back(0);
ivec.push_back(1);
ivec.push_back(2);
print_vec(ivec.begin(), ivec.end());
return 0;
}
these are the compilation errors: 这些是编译错误:
tia.cc:7:22: error: template declaration of 'bool print_vec' tia.cc:7:22:错误:'bool print_vec'的模板声明
tia.cc:7:37: error: expected ')' before 'itr' tia.cc:7:37:错误:在'itr'之前预期为')'
tia.cc:7:42: error: expected primary-expression before 'const' tia.cc:7:42:错误:“ const”之前的预期主表达式
tia.cc: In function 'int main()': tia.cc:在函数'int main()'中:
tia.cc:25:39: error: 'print_vec' was not declared in this scope tia.cc:25:39:错误:未在此范围内声明'print_vec'
thanks in advance. 提前致谢。
The type of the container is not deducible from the type of the iterator. 容器的类型不能从迭代器的类型推导出。 You can simply transform the template into:
您可以将模板简单地转换为:
template <typename Iterator>
bool print_vec(Iterator itr, const Iterator end)
{
for (; itr != end; ++itr) {
std::cout << *itr << std::endl;
}
return true;
}
First problem: You have not used typename
. 第一个问题:您尚未使用
typename
。 Wherever a type depends on a template argument, you must prefix the type with typename
. 无论类型取决于模板参数,都必须在类型
typename
加上typename
。
Secondly, the compiler cannot infer type
. 其次,编译器无法推断
type
。 It can only see the type of ivec.begin()
and has no idea about any other types that might have it as a typedef. 它只能看到
ivec.begin()
的类型,并且不知道其他任何可能将其作为typedef的类型。 You can only take the const_iterator
directly- you can't take a T::const_iterator
- without passing T
explicitly, anyway. 您只能直接采用
const_iterator
您不能采用T::const_iterator
无论如何都必须显式传递T
The best solution would be to template in terms of iterator types, since the container's type cannot be deduced from the function arguments: 最好的解决方案是使用迭代器类型作为模板,因为不能从函数参数推导出容器的类型:
template <typename Iterator>
bool print_vec(Iterator itr, Iterator end) { .... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.