Learning template programming

Hi,

I am trying to learn C++ programming and I am now looking on how to use templates.

My code looks as follows, I have one file called first.cpp and one called second.cpp and second.h.

first.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <iostream>
#include <stdlib.h>
#include "second.h"
using namespace std;

int main(){
	printWTF();
	int a,b;
	cout<<"Type in number a: "<<endl;
	cin >> a;
	cout<<"Type in number b: "<<endl;
	cin >> b;
	change(a,b);
	cout<<"Swaped: "<<a<<" "<<b<<endl;
	return 0;
}


second.h:
1
2
3
4
5
6
7
8
9
#ifndef _SECOND_H_
#define _SECOND_H_
#include <iostream>
#include <stdlib.h>
using namespace std;

void printWTF();
template <class T> void change(T &a, T &b);
#endif 


second.cpp:
1
2
3
4
5
6
7
8
9
10
11
#include "second.h"

void printWTF(){
	cout<<"WTF"<<endl;
}

template <class T> void change(T &a, T &b){
        const T tmp = a;
	a = b;
	b = tmp;
}


When I compile it using g++ first.cpp second.cpp -o first I get:

first.cpp:(.text+0x2d): undefined reference to `void change<int>(int&, int&)'
collect2: ld returned 1 exit status


Any help would be appreciated!

/Erik
Last edited on
You have to put the entire definition of the template in the header file. The reason is the compiler basically creates a new function (in this case) with T replaced by the proper type, and to do that it needs the entire definition available when it hits line 13 in first.cpp and needs to make that replacement.
I see, thank you! Can you do something else to make it work? So that you only have the prototype (correct?) in the header and the definiton in the second.cpp file?

/ Erik
Last edited on
comment removed
Last edited on
Zhuge has already explained what the problem is.
Yes, sorry about that.
Topic archived. No new replies allowed.