I thought I was starting to get the hang of 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:37: error: expected ')' before 'itr'
tia.cc:7:42: error: expected primary-expression before 'const'
tia.cc: In function 'int main()':
tia.cc:25:39: error: 'print_vec' was not declared in this scope
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
. Wherever a type depends on a template argument, you must prefix the type with typename
.
Secondly, the compiler cannot infer 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. You can only take the const_iterator
directly- you can't take a T::const_iterator
- without passing T
explicitly, anyway.
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) { .... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.