Mail Archives: djgpp/1998/03/19/20:01:08
Hmn, okay I have two suggestions. First off, there are already some GREAT
little templates for things like lists, they are called STL and are included
with GCC. They work fine for me, you can simply #include <list.h> and then
use them. You may need a tutorial for STL, I don't know. But you probably
want to make them yourself as an excercise, so I'll help out:
>in LIST.H
>
>#ifndef LIST_H
>#define LIST_H
>
>template<class T> class List {
> private:
> public:
>};
>
>#endif
I don't understand? You have no functions or data members on your list? Is
that intentional so you get a feel for templates or did you leave it out?
>in list.cc
>
>include "list.h"
>
>// Implementations go here
Okay, I think I understand. You left your implementations and details out to
simplify putting it to the NG. Okay, well here is your problem anyways. Think
of what happens when you compile your program using a template. The compiler
looks for a for the template info and then expands it, basically, for your
specified data type. So that if you use list<int> it makes all the functions
etc. for int, list<my_special_class_with_overloaded_operators> obviously
needs to be much different as it calls overloaded ops, etc. And I don't
really know exactly how this works. The problem is that it isn't comipling
your funtions list<int>::myfunc() because you haven't told it to. You've just
given it empty definitions (in list.cc) of HOW to compile them, but no data
types to actually compile them from. Now, I believe there are two solutions.
You can either put dummy statements of some kind into list.cc, for instance:
list<int> dummylist;
Or perhaps there is a way to do it without having to make a data member which
wastes space when you go to run your program. But at any rate this will
generate code for an int list. Or you could do it the way I do; put all the
executable code into the .h file. This will make things a bit bloated as
the code will get repeated in every source file it's used (i.e., it will be
generated in main.cc for list<int>, but a totally different one wil also be
made if say you linked in a groo.cc using list<int>, even though they are
identical codes; I did read somewhere about there being an optimization in
the works for this, maybe gcc 2.8.0 is smart enough to keep track of separate
source files' templated instantiation thingies, I don't know), but that's
just the price you pay for templates. And remember they are FAST at run time,
zoom zoom zoom so if they make things a bit FAT and SLOW compile time they
are probably still worth it! So GOOD LUCK!
PS the all-in-h-file approach is what the STL uses, but if you decide to
compile with STL you also have to include a library libstdcx or something, I
forget which one. You will see it!
- Calvin -
- Raw text -