c++templates

Officially, what is typename for?


On occasion I've seen some really indecipherable error messages spit out by gcc when using templates... Specifically, I've had problems where seemingly correct declarations were causing very strange compile errors that magically went away by prefixing the typename keyword to the beginning of the declaration... (For example, just last week, I was declaring two iterators as members of another templated class and I had to do this)...

What's the story on typename?


Solution

  • Following is the quote from Nicolai M. Josuttis's book "The C++ Standard Library":

    The keyword typename was introduced to specify that the identifier that follows is a type. Consider the following example:

    template <class T>
    Class MyClass
    {
      typename T::SubType * ptr;
      ...
    };
    

    Here, typename is used to clarify that SubType is a type of class T. Thus, ptr is a pointer to the type T::SubType. Without typename, SubType would be considered a static member. Thus

    T::SubType * ptr
    

    would be a multiplication of value SubType of type T with ptr.