2

I have read the book named C++ primer and I don't understand the following code:

typedef typename std::vector<int>::size_type size_type;

Could you help me explain the use of typename here?

chris
  • 55,166
  • 13
  • 130
  • 185
uttp
  • 102
  • 5
  • 4
    its called dependent type, the typename keyword is a grammar disambiguator to differentiate from function declaration. there are already many questions about it. http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords?lq=1 – v.oddou Dec 19 '13 at 06:26
  • 2
    Note that it is completely unnecessary here. – chris Dec 19 '13 at 06:33
  • 1
    To be clear: you do **not** need `typename` here. You *would* need it in `template struct Foo { typedef typename std::vector::size_type size_type; };` – juanchopanza Dec 19 '13 at 06:46

1 Answers1

1

You can read typedef typename std::vector::size_type size_type like this:

typedef typename std::vector::size_type size_type, just like typedef __int64 INT64.

Why we need typename beforce std::vector::size_type? It just tells the compiler that std::vector::size_type is a type not a normal class member. It's used for disambiguation.

But I think maybe some compiler can auto detect std::vector::size_type is a type.

So, typedef just creates an alias for an existing type, and typename tells the compile that std::vector::size_type is a type not a normal class member.

WKPlus
  • 6,106
  • 1
  • 32
  • 50