Vinod
Vinod

Reputation: 1091

Class template and type

template<typename T>class node{};

Now, if I were to use the following template definition in my .hpp file

template<typename node<T>> class list{};

the code doesn't compile:

Compiler Log

But if I were to change the definition to

template<typename X> class list{};

And use node<string> to substitute for X during instantiation, everything works fine.

I would like to understand why the code doesn't compile in the first case? AFAIK, node<T> is a distinct type by itself just like X.

Appreciate your thoughts.

Upvotes: 0

Views: 50

Answers (1)

John Zwinck
John Zwinck

Reputation: 249552

As you discovered, this does not work:

template<typename node<T>>

That's because the token after typename is supposed to be the name given to a template argument, not the combination of a name (T) and an existing type.

If you want to constrain your template class to make sure the thing it uses is a node, you can either do this:

template<typename T>
class list{ /* use node<T> here */ };

Or this, if you merely want to make it a suggestion and not a hard requirement:

template<typename T, typename N = node<T>>
class list{ /* use N here */ };

In either of these cases, list<int> will use node<int> internally.

Upvotes: 1

Related Questions