hello, quick question regarding template classes and pointers. I'm making a linked list kind of container system, and I'm running into trouble with it when I (don't know if the terminology is 100% correct here) declare an instance of it. An example would be best to explain what's happening:

I tried the following just to see if it would work ok, on one I get linker issues, on the other, it's fine.

Link<int> test1; //linker error

Link<int> test2(); //compiles fine

Link<int> *test3 = new Link<int>(); //linker error
delete *test3;

Is there something special I need to do to a class to make it able to be a pointer? The rest of the data structure follows, it's quite bare at this point. Thanks!


#include "link.h"

template <class T>
	size = -1;
	nextLink = NULL;

template <class T>
class Link
		Link<T> *nextLink;
		int size;

7 Years
Discussion Span
Last Post by jesseb07

Looks to me that you are not creating an instant of the template class
for <int>.

You have put the link body in a .cpp file. That is perfectly acceptable and good practice if the body is large. BUT you have not created an explicit instance of it.

So add
template class Link<int>;
at the bottom of your Link.cpp and I think that all will be fine.

Note: notice that your second case is actually a declaration to a function that is not used, that returns a Link<int>. Hence it compiles.

Edited by mike_2000_17: Fixed formatting


that fixed it, thanks. This is the first time I've used template classes in C++, so I have to create an explicit declaration for each variant of the class? I'm used to the C# way of doing templates where the compiler does all that for me.

So, say I wanted to be able to have a Link of types int, double, long, and string, I'd need to include all of this at the bottom?

template class Link<int>;
template class Link<double>;
template class Link<long>;
template class Link<string>;



The second case is not a declaration of Link<int> instance (object), that's why it was "compiled fine". It's a prototype of a function (never called) without parameters returned Link<int> object.

Most of C++ compilers can't process programs with separated template definition and implementation. Move Link template constructor from list.cpp to list.h.
Now correct the 3rd case (wrong delete *test3 ). It's not a linker error ;)

All done.


Thanks for the help. In my defense my copy-paste is broken so I was typing my code here by hand, which is why I said

Link<int> *test3 = new Link<int>();
delete *test3; //doh error

was a linker error when it should have been (and is)

Link<int> *test3 = new Link<int>(); //linker error
delete test3;

my mistake :P


This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.