Skip to main content
GameDev.net gamedev.net
🔒 Locked

typedef iterator problem

Started by wanzi Apr 26, 2006 at 5:58 AM 4 replies 4.4k views
Original Post
wanzi
wanzi
Ok, I've got the following code

template<typename T>
class Test
{
public:
	void Foo()
	{
		typedef std::vector<T>::iterator vec_itor;	// 1
	}

	typedef std::vector<T> vec_type;			// 2
	typedef std::vector<T>::iterator vec_itor;		// 3!!(Problem)
};

The compiler gives error for 3, saying "std::vector::iterator : dependent name is not a type". If I comment out 3, it runs properly. What puzzels me is that wht 1 and 2 work, but 3 doesn't. Aren't 1 and 3 basically the same??
Enigma
Enigma
The problem is known as "dependant name lookup", or "two-phase name lookup". Basically the compiler cannot know whether std::vector< T >::iterator is a type or a static member until it knows the type T (because of possible template specialisations). Therefore you must tell the compiler that std::vector< T >::iterator is a type by using the typename keyword:

typedef typename std::vector< T >::iterator vec_itor;.

I don't know why #1 works. I don't believe it should and gcc agrees with me. I'd advise adding typename into that line as well.

Σnigma
wanzi
wanzi
Thanks for the quick reply~~~~

For anyone interested in "Two-Phase Name Lookup", I just found a codeproject article http://www.codeproject.com/cpp/TwoPhaseLookup.asp
Emmanuel Deloget
Emmanuel Deloget
Enigma, doesn't #1 work because if Foo() is not called, it is not instantiated (and thus not compiled) - and if Foo() is called, vector is known (and vector::iterator is then known as a type)?

template <class T> class A{public:   typedef std::vector<T> vec_type;   typedef typename std::vector<T>::iterator iter_type;   void foo()   {      I can put whatever I want here.   }};

The code compiles correctly unless foo() is called.

Without this feature, metaprogramming using templates would be rather hard :)

Regards,
Polymorphic OOP
Polymorphic OOP
Quote:
Original post by Emmanuel Deloget
Enigma, doesn't #1 work because if Foo() is not called, it is not instantiated (and thus not compiled) - and if Foo() is called, vector is known (and vector::iterator is then known as a type)?

While that may very well be happening with whatever compiler is being used, that is not correct behavior. The error should occur as soon as the template definition is encountered, not when it is being instantiated.
stylin
stylin
Yes, the compiler should (does) try to validate all execution paths, even the ones that get optimized out. This is a good thing so we can take advantage of some of the more obscure metaprogramming techniques (like compile-time short-circuiting on 0-length array declarations).
:stylin: "Make games, not war." "...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.