I am a beginner both in programming and in C++. I have used templates before but in a very limited way and I have no idea what I am doing wrong:
template <typename TElement>
struct list{ // if I try list<TElement> => list is not a template
TElement data;
struct list *next;
} node_type; // also tried node_type<TElement>, other incomprehensible errors
node_type *ptr[max], *root[max], *temp[max];
I find the error a bit incomprehensible: "node_type does not name a type"
What am I doing wrong ?
What I intend to do:
I want to have a list of type (so I can use this on several completely different Abstract Data Types – ADTs), so I’d like to end up with something like this:
Activities list *ptr[max], *root[max], *temp[max]
if that makes any sense (Where Activities is a class but can be any other class).
Don’t try to learn C++ by trial and error and guessing at the syntax, read a good book.
This declares a struct template called
listwhich has a single template parameter,TElement, which serves as an alias (only within the body of the template) for the type you instantiate the template with.If you instantiate
list<int>thenTElementwill refer toint.If you instantiate
list<char>thenTElementwill refer tochar.etc.
So the type you instantiate the template with will be substituted for
TElementin your template definition.The error you got when trying:
is because this is not valid syntax, the error is telling you
listisn’t a template because at the point where you writelist<TElement>you haven’t finished declaringlistyet, so the compiler has no idea what it is and you can’t have a list of something if the list template isn’t defined.This attempts to declares an object of type
list, similar to this syntax:But in your case
listis not a type, it’s a template.list<int>is a type, butliston its own is not a valid type, it’s just a template that a type can be made from when you “fill in the blanks” i.e. provide a type to substitute for the parameterTElementIt looks like you weren’t even trying to declare a variable anyway, just blindly guessing at syntax.
That won’t help either,
node_type<TElement>is nonsense, if you want to declare a variable it needs a type, e.g.list<int>. The parameterTElementneeds to be replaced with a type, it isn’t a type itself. Stop trying to string together random bits of syntax hoping it will work. You could start by reading http://www.parashift.com/c++-faq/templates.htmlOn the last line:
node_typeisn’t a type so that won’t work. Also, you should avoid getting into the bad habit of declaring multiple variables on a single line. It’s much clearer to write:Instead of
Also, are you sure youu want arrays of pointers? Since you clearly don’t know what you’re doing it would be more sensible to use standard container types that do the work for you.