简体   繁体   中英

How do I write a function that can iterate over a generic type

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.

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';
}

As stated, this will only work if you have the requisite std::ostream& operator<<(...) overload.

You would call it as follows:

int main()
{
    std::vector<int> myvec;

    // populate myvec...

    print_all(std::begin(myvec), std::end(myvec));
    return 0;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM