Templates and undefined reference to

I am reading about templates.

I have created a list.h file containing this code:
1
2
3
4
5
6
7
8
// list.h
template <class T>
class List
{
   public:
   List(){}
   virtual ~List(){}
}

When I include that file into my main.cpp it all compiles and I can create generic lists.

But, if I write the List constructor in list.cpp (and change "List(){}" to just "List();" in list.h), it fails:
1
2
3
4
5
6
//list.cpp
#include "list.h"
template <class T>
List<T>::List()
{
}


The error I get is "main.cpp:10: undefined reference to `List<int*>::List()'"

What am I doing wrong?
Double-check your book/tutorial on templates. It should have mentioned that template declaration and definition must all be in the same code file. Meaning: You cannot split the template in two files. Meaning: Write the whole thing in List.h.
Have a look here: http://newdata.box.sk/bx/c/htm/ch19.htm#Heading8, heading "Using the Name".

It says:

"Within the class declaration, the word Array may be used without further qualification. Elsewhere in the program, this class will be referred to as Array<T>. For example, if you do not write the constructor within the class declaration, you must write
1
2
3
4
5
6
7
8
template <class T>
Array<T>::Array(int size):
itsSize = size
{
pType = new T[size];
for (int i = 0; i<size; i++)
pType[i] = 0;
}

The declaration on the first line of this code fragment is required to identify the type (class T). The template name is Array<T>, and the function name is Array(int size)."

What I understand of the bold text is that you can write the constructor outside the class definition, e.g. in a .cpp file. Right?
Nope. You can write the constructor outside the class declaration, but you must still be in the same file.
Strange, because I get exactly the same error if I have everything declared in the header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
// list.h
template <class T>
class List
{
   public:
   List();
   virtual ~List(){}
};

template <class T>
List<T>::List()
{
}


Am I still missing something?
Looks good to me. What compiler are you using? Furthermore, ideone.com says it is OK. See https://ideone.com/T8CDw .
gcc version 4.1.2.
Maybe it is just the compiler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <class T>
class List
{
   public:
   List();
   virtual ~List(){}
};

template <class T>
List<T>::List()
{
}


int main() {
	List<int> test;
	return 0;
}


This compiles fine for me. VC++ 2008.
Topic archived. No new replies allowed.