Another 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 the C++ class template specialization to accommodate many data types

To show: How to create the class template specialization to use many data types in C++ programming

 

// another C++ class template specialization example

#include <iostream>

using namespace std;

 

template <class any_data_type>

any_data_type MyMax(any_data_type Var1, any_data_type Var2)

{

return Var1 > Var2 ? Var1:Var2;

}

 

// specialization of MyMax() for char *

template<>char* MyMax(char* Var3, char* Var4)

{

return strcmp(Var3,Var4)> 0 ? Var3:Var4;

}

 

int main(void)

{

// using the class template with different data types

cout<<"MyMax(10,20) = "<<MyMax(10,20)<<endl;

cout<<"MyMax('Z','p') = "<<MyMax('Z','p')<<endl;

cout<<"MyMax(1.234,2.345) = "<<MyMax(1.234,2.345)<<endl;

char* Var3 = "Function";

char* Var4 = "Template";

cout<<"\nTesting...."<<endl;

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

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

cout<<"MyMax(\"Function\",\"Template\") = "<<MyMax(Var3,Var4)<<endl;

return 0;

}

 

Output examples:

 

MyMax(10,20) = 20

MyMax('Z','p') = p

MyMax(1.234,2.345) = 2.345

Testing....

Address of *Var3 = 0012FF60

Address of *Var4 = 0012FF54

MyMax("Function","Template") = Template

Press any key to continue . . .

 

 

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