1

I have to declare Iter as typename but no typedef.
Then, I cannot use Iter in my template class declaration => frustrating :(
Please teach me how to use Iter, or else explain me why C++ is so nasty...

template <typename T>
struct MyContainer
{
  typedef  std::vector<T>  Vec;
  typename Vec::iterator   Iter;

  void Fo (typename std::vector<T>::iterator);  //ok
  typename std::vector<T>::iterator Ba();       //ok

  void Foo (Iter);   //error: 'Iter' is not a type
  Iter Bar ();       //error: 'Iter' does not name a type
};                   //(gcc 4.1.2)
  1. Why typedef cannot be used to declare Iter? Why not?
  2. How to use Iter within the template class? (e.g. as function parameter type)

EDIT
In the instruction typename Vec::iterator Iter; the keyword typename says Vec::iterator is a type (i.e. not a static member function/attribute). Therefore, Iter is not declared as a type, but as a variable using the type Vec::iterator.

Community
  • 1
  • 1
oHo
  • 51,447
  • 27
  • 165
  • 200

3 Answers3

8
  1. typedef can be used alongside typename. So it becomes:

    typedef typename vec::iterator Iter;
    
  2. Just use Iter now.

    template <typename T>
    struct MyContainer
    {
      typedef  std::vector<T>         Vec;
      typedef typename Vec::iterator  Iter;
    
      void Foo (Iter);   //ok
      Iter Bar ();       //ok
    };
    
oHo
  • 51,447
  • 27
  • 165
  • 200
Lyubomir Vasilev
  • 3,000
  • 17
  • 24
  • perfect :) I have just added in your answer the code source solution :-D thanks ;) – oHo Oct 19 '12 at 08:08
  • 1
    @olibre Regarding your edit to this answer (which I've rolled back): It is possible to use blockquote within enumerations by indenting twice (4 + 4 = 8 spaces). No need for any unusual enumeration syntax... – jogojapan Oct 19 '12 at 08:21
  • 1
    @jogojapan Thank you for your tip/advice :-D – oHo Oct 19 '12 at 08:26
3

Just to add to the previous answer...

typename Vec::iterator   Iter;

is a valid C++ statement which declares not a type but a variable named Iter.

The keyword typename was introduced to specify that the identifier that follows is a type. When parsing Vec::iterator, the compiler is unable to recognize that iterator means a type, because it is a template-dependent name. It could be as well a static data member in Vec.

Officially, what is typename for?

Community
  • 1
  • 1
Andriy
  • 8,486
  • 3
  • 27
  • 51
1

This line:

typename Vec::iterator   Iter; 

Declares a member variable called Iter, of type Vec::iterator (i.e. vector<T>::iterator), and not a type.

Looking at what you did after this you probably meant:

typedef  typename Vec::iterator   Iter; 
CashCow
  • 30,981
  • 5
  • 61
  • 92