1

This bit of code if from an example for a linked list but I'm struggling to understand the 2nd line of this function, could someone talk me through it?

template <typename T>
typename List<T>::Node* List<T>::search(T d)
{
    if(!head) return NULL;
    Node* cur = head;
    while(cur) {
        if(cur->data == d) return cur;
        cur = cur->next;
    }
    return NULL;
}    
James Gillard
  • 31
  • 1
  • 4

3 Answers3

3

There will be a *type* Node somewhere in the List<> class template (or specialization) so when referring to that type the syntax typename List<T>::Node must be used.

Dependant names can be disambiguated with the typename keyword.

sehe
  • 374,641
  • 47
  • 450
  • 633
DrYap
  • 6,525
  • 2
  • 31
  • 54
  • Why a typedef? Could be an enum, a struct or a class. Even a template alias. So you meant: there will be a nested typename in the `List<>` _specialization/instantiation_ – sehe Aug 08 '13 at 15:49
  • You're right. I've had this problem with typedefs recently so I was a bit blinkered, thanks. – DrYap Aug 08 '13 at 15:53
  • 1
    I added "or specialization" as this is really _the_ reason why the compiler really can't know all typenames at first pass (aside from CRTP, by the way). +1 for mentioning the relevant term "Dependent name" though – sehe Aug 08 '13 at 15:56
1

If you mean the second line in the your post, that says "Search is a function that takes an argument of type T and returns a pointer to a type specific to the Linked List called List<T>::Node.

If you mean the second line in the function search itself, it is just initializing a local var cur to a member variable called head (here likely referring to the head of the linked list data st.). The rest of the code just iterates our the elements of the list until a node containing data that's being searched is found and returned.

Arun R
  • 873
  • 6
  • 10
  • Linked list data st.? I didn't know linked lists had their own patron saint these days. – sehe Aug 08 '13 at 15:57
0

Consider A<T>::X. X could be a type (typedef, struct, etc) or it could be variable (static variable). When you are "inside" a template, and use a type which has a template in this fashion, you must help the compiler by adding typename if your X is a type.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91