I want to write a function like print_all
described below.
#include <iterator>
#include <vector>
template <typename V>
void print_all(std::iterator<std::input_iterator_tag, V> it) {
for (; it != std::end(it); ++it) {
V item = *it;
// do stuff with item
}
}
int main() {
std::vector<int> myvec (10);
print_all(myvec.cbegin());
return 0;
}
How do I declare print_all
such that it can accept any iterator over type V
?
Edit
I want to do this in a typesafe way. A better example of a use case would be an accumulator
#include <iterator>
#include <vector>
#include <functional>
template <typename V, typename K>
K accumulate(
std::function<K(K, V)> accumulator,
std::iterator<std::input_iterator_tag, V> it,
std::iterator<std::input_iterator_tag, V> end,
K initial) {
K sum = initial;
for (; it != end; ++it) {
V item = *it;
sum = accumulator(sum, item);
}
return sum;
}
Now you see why this question is not a duplicate of this. I feel like there would be a typesafe way to do this where the compiler makes sure the iterator iterates over the correct type. That is why I hesitate to accept Steve Lorimer's answer.