defining iterator in a template class

I couldn't find a reasonable title for the question, sorry.
I try to wrap a map container to make it thread-safe. I wrote the below class but i get compile error.I couldn't find what the problem is... I define just an iterator for a map, but the compiler complains..
What am I missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
template <class Key, class Item>
class ItemDb
{
	public:
		void Insert(const Key& key, const Item& item)
		{
			_container.insert(std::pair<Key, Item>(key, item));
		}
		void Fetch(int n, std::list<Item>& returnList)
		{
			std::map<Key, Item>::iterator it; //<---------COMPILE ERR
			std::map<Key, Item>::iterator end = _container.end(); //<---------COMPILE ERR

			for (it=_container.begin(); it!=end; ++it)
			{
				returnList.push_back( it->second );
			}
		}
		int Size() const
		{
			return _container.size();
		}
	protected:
	private:
		std::map<Key, Item> _container;
};


Compile error:
mapfill.cpp: error: expected ‘;’ before ‘it’
mapfill.cpp: error: expected ‘;’ before ‘end’

Last edited on
It compiles for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <map>
#include <list>

template <class Key, class Item>
class ItemDb
{
	public:
		void Insert(const Key& key, const Item& item)
		{
			_container.insert(std::pair<Key, Item>(key, item));
		}
		void Fetch(int n, std::list<Item>& returnList)
		{
			std::map<Key, Item>::iterator it; //<---------COMPILE ERR
			std::map<Key, Item>::iterator end = _container.end(); //<---------COMPILE ERR

			for (it=_container.begin(); it!=end; ++it)
			{
				returnList.push_back( it->second );
			}
		}
		int Size() const
		{
			return _container.size();
		}
	protected:
	private:
		std::map<Key, Item> _container;
};

int main() {
    return 0;
}
My compiler is:
g++ (GCC) 4.4.2 20091027 (Red Hat 4.4.2-7)
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
The compiler doesn't know map::iterator is a type. You have to give it a hint:

1
2
typename std::map<Key, Item>::iterator it;
typename std::map<Key, Item>::iterator end = _container.end();
@xyzt: On both error lines you need to use the keyword "typename" in front.

@R0mai: You need to get a compliant compiler :)

@R0mai: You need to get a compliant compiler :)

You may be right, I thought VC++2010 is enough complaint:)
Thanks! typename solved it.
R0mai:

Was that just a typo or a freudian slip? :)

(complaint vs. compliant)
Was that just a typo or a freudian slip? :)

I have to admit, it was a typo, but a rather funny one :)
I just looked up both words in the dictionary to see what's the difference, so if it was a freudian slip it had to be really unconscious.
Topic archived. No new replies allowed.