templates in two separate (.h and .cpp files)

Jan 16, 2013 at 8:33am
Hi every one.
I am stuck in a difficult problem and really need its solution.
The problem is in these three code files:

First File: .h file
Second File: .cpp file
Third File: .cpp (File with a main function to run the program)

(All files code is written in Visual-Studio 2008 .net 3.5 (C++)).

First File: It is a ".h" file.

1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
template <typename T>
class Temp
{
private:
	T* data;
public:
	Temp(void);
	void Set_Temp(T* var = NULL);
	T* Get_Temp();
	~Temp(void);
};
//.h file end. 


Second File: It is a ".cpp" file of above ".h" file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "Temp.h"
template <typename T>
Temp<T>::Temp(void):data(NULL)
{}
template <typename T>
void Temp<T>::Set_Temp(T* var = NULL)
{
	this->data = var;
}
template <typename T>
T* Temp<T>::Get_Temp()
{
	return this->data;
}
template <typename T>
Temp<T>::~Temp(void)
{
	delete this->data;
}
//.cpp file end. 


Third File: It is a ".cpp" file with a main function to run the program.

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
#include "Temp.h"
void main()
{
	Temp<int> *ptr = new Temp<int>();
}


Story and problem:
I made a new Empty Project. Wanted to implement the above code but it returned me these two errors:

Error 2 fatal error LNK1120: 1 unresolved externals C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\AB\Debug\AB.exe 1

Error 1 error LNK2019: unresolved external symbol "public: __thiscall Temp<int>::Temp<int>(void)" (??0?$Temp@H@@QAE@XZ) referenced in function _main Main.obj


I searched allot on the internet but it didn't worked for me.
I really need a solution so plz plz help me for this.
And plz state any mistake in the code if.
Last edited on Jan 16, 2013 at 8:36am
Jan 16, 2013 at 8:36am
Generally speaking, the template code that appears in Temp.cpp must go in a header file.
Jan 16, 2013 at 11:48am
Actually my aim is to keep .h's code in .h file ,and .cpp's code in .cpp file.

And want to execute this statement:

Temp<int> *ptr = new Temp<int>();
Jan 16, 2013 at 11:58am
The template code has to be available when you use it. If you want to have it in two files you can include the other file from the header.

#include "Temp.cpp"

But it is probably best to use some other file extension than .cpp in that case.
Topic archived. No new replies allowed.