Using templates in struct -- to make a generic linked list
In .NET I really liked System.Generic.List and wanted to replicate it as a way of learning the C++ language. The problem is that I want it to be generic, I want the elements to contain a value of a template type T. I know most of what to do, but the problem lies within the node.
template<class T>
struct node
{
T value;
bool isFirst;
node *next;
}开发者_开发百科;
I have tried googling this for a while and haven't found anything relevant. I have just gone through the tutorials at www.cplusplus.com. Do I have to reference the class here with a pointer, if so, how?
Thanks in advance
Gisle Aune
There's nothing wrong with your code. Actually, I would probably write it as
template<class T>
struct node
{
T value;
bool isFirst;
node<T> *next;
};
because it's not much more verbose and it's clearer that next
points to a node
of the same type, but nevertheless also your version is fine: in a template, when you use the name of the class without explicitly specifying the template parameters, it's implied that they are the same ones of the template being currently instantiated. This is explained at §14.6.1 of the C++ standard:
Within the scope of a class template, when the name of the template is neither qualified nor followed by <, it is equivalent to the name of the template followed by the template-parameters enclosed in <>. [Example: the constructor for
Set
can be referred to asSet()
orSet<T>()
. ] Other specializations (14.7.3) of the class can be referred to by explicitly qualifying the template name with the appropriate template-arguments. [Example:
template<class T> class X {
X* p; // meaning X<T>
X<T>* p2;
X<int>* p3;
};
—end example]
By the way, writing a generic list is a useful exercise to learn the language, but keep in mind that many generic containers are already available in the C++ standard library; besides the fact that they are throughly tested and optimized, their "iterators" abstraction allow you to use on almost any container the freestanding algorithms available in the library.
this code is correctly written. Anyway, if you want to use generic lists in c++, you could use stl
#include <list>
std::list<int> lista;
精彩评论