Reputation: 117
This is the example-implementation of the count algorithm from https://devdocs.io/cpp/algorithm/count_if:
template<class InputIt, class T>
typename iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value)
{
typename iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first) {
if (*first == value) {
ret++;
}
}
return ret;
}
My question is, what is the significance of typename iterator_traits<InputIt>::difference_type
?
If I were implementing this, I would have simply used unsigned int
to keep track of the count.
Upvotes: 1
Views: 1353
Reputation: 292
typename tells the compiler that iterator_traits::difference_type is of type class.
Consider an easier to understand example:
class ...
{
typename T::Something *p;
}
Without the typename, the compiler may try to create a static member which will contain the result of T::Something multiplied by p;
while when you state typename, the compiler is certain to know that p is a pointer of type T::Something
Hope this helps.
Upvotes: 0
Reputation: 45684
Well, you cannot know the best sufficiently-large type the difference between two iterators without knowing anything about the iterators.
As an example, what if the iterator iterates the bytes in a file:
The filesize is 64bit, but we are in a 32bit process. std::size_t
won't work, likely unsigned
won't either.
Thus, ask std::iterator_traits
to generically provide a suitable type.
Now, we have to use typename
there to assure the compiler that the dependent qualified name std::iterator_traits<InputIt>::difference_type
will be a type. That is important to clarify for 2-phase lookup.
Upvotes: 4