0

In my program, I have a template class that can take as arguments any type of container, like std::vector, std::map, etc.

The goal is that my class can work with both vector iterators and map iterators. Right now it works with vector iterators, for example they do stuff with the vector iterators as arguments. Small example:

template <class T>
class Example
{
private:

public:
    Example() {}
    void someMethod(typename T::iterator it)
    {
        cout << *it;
    }
};

If I use Example< vector<int> > example, and use someMethod with some iterator, the method will just print an int from the vector.

But if I will use Example < map<int, int> > and pass a map<int, int>::iterator as argument in someMethod it will not work, because I would have to change the *it in someMethod to it->first or it->second (depending on what I want to print, key or value).

My question: is there a way I could pass a map iterator that would actually be an iterator to the key / value so I don't have to touch any method in my class?

  • [Are you looking for this](https://stackoverflow.com/a/35262398/7691729)? There isn't anything like this in STL unfortunately. – Quimby May 21 '22 at 16:21
  • Yeah, that's what I was looking for. I guess I have to write something like a custom iterator, right? –  May 21 '22 at 16:25
  • 2
    @Quimby : There is as of C++20: [`std::views::keys`](https://en.cppreference.com/w/cpp/ranges/keys_view) and [`std::views::values`](https://en.cppreference.com/w/cpp/ranges/values_view) – ildjarn May 21 '22 at 16:25
  • First you can always define an `operator <<` for pair. But that's not really flexible. Better to add a second argument to `someMethod` for printing `*it`. You can specify a default so you only have to give the second argument when `*it` doesn't have an `operator <<` itself or you want a custom printer. – Goswin von Brederlow May 21 '22 at 16:33

0 Answers0