A very simple C++ class template specialization 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: Creating and using the C++ class template specialization to accommodate different types of data in C++ programming

To show: How to create and use the C++ class specialization template to accommodate different types of data in C++ programming

 

// C++ template specialization

#include <iostream>

#include <string>

using namespace std;

 

template <class any_data_type>

inline any_data_type MyMax(const any_data_type& Var1, const any_data_type& Var2)

{

cout<<"Checking..."<<endl;

return Var1 < Var2 ? Var2 : Var1;

}

 

// do some testing

int main(void)

{

int Highest = MyMax(7, 20);

char p = MyMax('x' , 'r');

string Str1 = "Class", Str2 = "Template";

string MaxStr = MyMax(Str1, Str2);

cout<<"The bigger between 7 and 20 is "<<Highest<<endl;

cout<<"The bigger between 'x' and 'r' is "<<p<<endl;

cout<<"The bigger between \""<<Str1<<"\" and \""<<Str2<<"\" is "<<MaxStr<<endl<<endl;

const char *Var3 = "Class";

const char *Var4 = "Template";

const char *q = MyMax(Var3, Var4);

cout<<"Logical error, comparing the pointer, not the string..."<<endl;

cout<<"Address of the *Var3 = "<<&Var3<<endl;

cout<<"Address of the *Var4 = "<<&Var4<<endl;

cout<<"The bigger between \""<<Var3<<"\" and \""<<Var4<<"\" is "<<q<<endl;

cout<<"Need specialization here..."<<endl;

return 0;

}

 

Output examples:

 

Checking...

Checking...

Checking...

The bigger between 7 and 20 is 20

The bigger between 'x' and 'r' is x

The bigger between "Class" and "Template" is Template

Checking...

Logical error, comparing the pointer, not the string...

Address of the *Var3 = 0012FEC0

Address of the *Var4 = 0012FEB4

The bigger between "Class" and "Template" is Class

Need specialization here...

Press any key to continue . . .

 

 

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