简体   繁体   中英

Regarding templates for struct in C++

Method 1:

 template <class T>
 struct node{
      T data;
      struct node *next;
 };

Method 2:

 template <class T>
 struct node{
      T data;
      struct node<T> *next; // different from above
 };

Both of them compiles and runs correctly for a linked list.

Isn't there a difference? If not, why?

There is no difference.

The reason that this is so is because, for convenience, within a templated class/struct, the naked name of that class/struct refers to the current template instantiation.

This feature becomes really handy if you have, say, six templated arguments that themselves have templated arguments, and you just want to declare a pointer :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM