Question

I try here to backward iterate multimap keys, function with hardcoded types works.

#include <map>
#include <string>
#include <iostream>
using namespace std;

multimap<int, string> mm = { {1, "a"}, {1, "lemon"}, {2, "peacock"}, {3, "angel"} };

void printKeysBackwards(multimap<int, string> mm) {
  typedef multimap<int, string> multimap_type;
  typedef std::reverse_iterator<multimap_type::iterator> reverse_iterator;
  for (auto it = mm.rbegin(), end = mm.rend(); it != end; 
     it = reverse_iterator(mm.lower_bound(it->first))) {
    cout << (*it).first << endl;
  }
}

int main() {
  printKeysBackwards(mm);
  return 0;
}

But when I'm trying to template the function:

template <class Key, class Val>
void printKeysBackwards(multimap<Key, Val> mm) {
  typedef multimap<Key, Val> multimap_type;
  typedef std::reverse_iterator<multimap_type::iterator> reverse_iterator;
  for (auto it = mm.rbegin(), end = mm.rend(); it != end; 
     it = reverse_iterator(mm.lower_bound(it->first))) {
    cout << (*it).first << endl;
  }
}

Typedef tells me it doesn't like to be templated:

error: type/value mismatch at argument 1 in template parameter list for
  'template<class _Iterator> class std::reverse_iterator'
Was it helpful?

Solution

The problem stems from your usage of a name that depends on another template which you instantiate with your template parameters.

When the compiler first encounters multimap_type::iterator, which it knows really means multimap<Key, Val>::iterator it cannot know if iterator will be a type or not (after all, it does not know which instantiation of multimap will be chosen, since it knows neither Key nor Val).

Knowing whether a name represents a type is important for parsing however, so the compiler takes a guess - which is "not type".

If you wish to tell the compiler that this will be a type, you have to tell it so:

typedef std::reverse_iterator<typename multimap_type::iterator> reverse_iterator;

OTHER TIPS

Use typedef std::reverse_iterator<typename multimap_type::iterator> reverse_iterator;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top