0

I'm using an example from Stroustrup C++ 4th Ed Page 692. Does anyone know why typename must come before Iter::value_type? Specifically in relation to the second mean function, why is typename not required for this template function?

I have read through Stroustrup's book sequentially and am in the templates section. I do not recall reading about the reasoning behind this.

Thanks for your guidance!

template<typename Iter>
typename Iter::value_type mean(Iter first, Iter last);

template<typename T>
T mean(T*,T*);

void f(vector<int>& v, int* p, int n)
{
    auto x = mean(v.begin(),v.end());
    auto y = mean(p,p+n);
}
notaorb
  • 1,944
  • 1
  • 8
  • 18
  • 1
    In the 1st `mean()`, the `Iter::value_type` is *dependent* on what `Iter` is set to. The `value_type` could be a type, a constant, a member function, etc. So the extra `typename` is needed to let the compiler know that `value_type` is guaranteed to be a type, even when the type of `Iter` is not known yet. In the 2nd `mean()`, the compiler already knows that `T` is a type. – Remy Lebeau Jul 01 '20 at 22:40
  • 1
    Note that this has changed in c++20. You no longer need `typename` for this example. – cigien Jul 01 '20 at 22:41

0 Answers0