The C++ class template packaging program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: To package the C++ class template in an organized file structure

To show: How to do the C++ class template packaging


Create a new Win32 empty console mode application project. Add a header file named test.h to your project


// test.h file, add new header file to the project

// C++ class template packaging

#include <iostream>

using namespace std;


// a class template declaration part

template <class any_data_type>

class Test



// constructor


// destructor


// function template

any_data_type Data(any_data_type);



template <class any_data_type>

any_data_type Test<any_data_type>::Data(any_data_type Var0)

{return Var0;}


// a class template definition part

// should be in the same header file with the class template declaration a constructor

template <class any_data_type>


{cout<<"Constructor, allocate..."<<endl;}


// a destructor

template <class any_data_type>


{cout<<"Destructor, deallocate..."<<endl;}

// do not run this program

// make sure there is no error such as typo etc


Then add a new C++ source file named test.cpp. Add the following main() program code


// the main() program, add new C++ source file named

// test.cpp, compile and run this program

#include <iostream>

#include "test.h"

using namespace std;


int main(void)


Test<int> Var1;

Test<double> Var2;

Test<char> Var3;

Test<char*> Var4;

cout<<"\nOne template fits all data type..."<<endl;

cout<<"Var1, int = "<<Var1.Data(100)<<endl;

cout<<"Var2, double = "<<Var2.Data(1.234)<<endl;

cout<<"Var3, char = "<<Var3.Data('K')<<endl;

cout<<"Var4, char* = "<<Var4.Data("The class template")<<"\n\n";

return 0;



Output examples:


Constructor, allocate...

Constructor, allocate...

Constructor, allocate...

Constructor, allocate...

One template fits all data type...

Var1, int = 100

Var2, double = 1.234

Var3, char = K

Var4, char* = The class template

Destructor, deallocate...

Destructor, deallocate...

Destructor, deallocate...

Destructor, deallocate...

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index