user1254554
user1254554

Reputation: 203

Difference between template name and class template name

Suppose I have a class template as follows

template <class t>
class Node{
    T data;
    Node<T>* nxt;
}

My question is when we want a pointer to class Node, why cant we use Node* nxt and what is the difference between Node*<T> nxt and Node* nxt?

Upvotes: 0

Views: 82

Answers (2)

legends2k
legends2k

Reputation: 32904

what is the difference between Node*<T> nxt and Node* nxt?

There's no such type called Node. Node<T> would be a type, while Node is a template (not a type) from which you could make more types. Consequentially you could've a pointer to Node<T> but not to Node; hence Node<T>* is valid and Node* not.

My question is when we want a pointer to class Node

You don't want a pointer to the template class Node but to some specific type like Node<int>. Also note that Node<int> and Node<float> are completely different types, similar to how different say Animal and Pencil types are.

why cant we use Node* nxt

Because you can't make a pointer to a non-type entity. It's a template, not a type.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119219

Actually, it is valid to write Node* nxt in the class template definition, and it will have the same meaning as Node<T>* nxt. In general, inside the definition of a class template C with template parameters T1, T2, ... or such, you can simply write C and it will be equivalent to C<T1, T2, ...>. Try it, it will compile. (To be more precise, the type Node behaves as though it is declared as a nested type inside the class.)

Outside the class definition (and any member function definitions), you have to supply template parameters, rather than just writing Node by itself, because the name Node denotes a template, not a class; a class template is not a type, but a class obtained by instantiating a class template with template parameters is a type.

Upvotes: 2

Related Questions