1

Reading about iterators online, I came across this declaration of the std::distance function:

template<class InputIterator>
  typename iterator_traits<InputIterator>::difference_type // What is this line?
    distance (InputIterator first, InputIterator last);

The first and third lines are clear to me, but I don't entirely understand the syntax of the second line.

I understand that iterator_traits<InputIterator>::difference_type will generate a class from the iterator_traits class template in order to figure out the difference_type suitable for this particular InputIterator. Please correct me if my understanding is wrong.

But what I certainly don't understand is the use of typename in this context. I've never seen it outside a template < ... > clause.

Please explain this syntax and its usage.

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • https://en.cppreference.com/w/cpp/keyword/typename – Jesper Juhl May 24 '20 at 18:35
  • The short answer is that the compiler needs help determining that `difference_type` is a type as syntactically speaking it could be a static member variable. So `typename` is necessary to disambiguate the syntax in this case. – john May 24 '20 at 18:36
  • 1
    *"outside template"*, your are in template though... – Jarod42 May 24 '20 at 18:39
  • @john I see. Because `difference_type` is a *dependent name*, since its type depends on a template argument? – Aviv Cohn May 24 '20 at 18:44
  • @AvivCohn yes, this issue only arises with templates, with non-templates the compiler can just look at the class to determine what everything is. With dependent names in templates thats not possible in the general case. – john May 24 '20 at 18:46
  • 1
    @john Great! Got it, thank you. Voting to close. – Aviv Cohn May 24 '20 at 18:49
  • @AvivCohn I just learned from another SO question, that C++20 is proposing to relax the rules around typename. In cases where a type is the only legal option typename will no longer be required. – john May 25 '20 at 05:17
  • @AvivCohn See [here](https://stackoverflow.com/questions/61990971/why-dont-i-need-to-specify-typename-before-a-dependent-type-in-c20/61991157#61991157) – john May 25 '20 at 05:21

0 Answers0