如何编写一个可以遍历泛型类型的函数 [英] How do I write a function that can iterate over a generic type
问题描述
我想要写一个如下所述的 print_all
函数。
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;
}
如何声明 print_all
以便它可以接受 V
?
How do I declare print_all
such that it can accept any iterator over type V
?
我想以类型安全的方式做到这一点。一个更好的例子是一个累加器
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;
}
现在您会看到为什么此问题不是 this 。我觉得有一个类型安全的方式来做这个编译器确保迭代器迭代正确的类型。这是为什么我不愿意接受Steve Lorimer的回答。
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.
推荐答案
假设你有重载的 std :: ostream
运算符,您可以实际的迭代器你的函数模板的类型
Assuming you have the required overloaded std::ostream
operators, you can just make the actual iterator your function template's type
template<typename IterT>
void print_all(IterT begin, IterT end)
{
while (begin != end)
std::cout << *begin++ << ", ";
std::cout << '\n';
}
如上所述,只有当你有必要的 std :: ostream&
As stated, this will only work if you have the requisite std::ostream& operator<<(...)
overload.
您将这样调用:
int main()
{
std::vector<int> myvec;
// populate myvec...
print_all(std::begin(myvec), std::end(myvec));
return 0;
}
这篇关于如何编写一个可以遍历泛型类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!