The C++ class template specialization code 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 in C++ programming

To show: How to create and use the C++ class template specialization in C++ programming

 

// C++ template specialization

#include <iostream>

#include <string>

// for strcmp()

#include <cstring>

using namespace std;

 

// primary template, for all type

template <class any_data_type>

any_data_type MyMax(const any_data_type Var1, const any_data_type Var2)

{

cout<<"Primary template..."<<endl;

return Var1 < Var2 ? Var2 : Var1;

}

 

// specialization for const char *, empty parameter list

template <>

const char *MyMax(const char *Var1, const char *Var2)

{

cout<<"Specialization..."<<endl;

// comparison for const char *

return (strcmp(Var1, Var2)<0) ? Var2 : Var1;

}

 

// do some testing

int main(void)

{

// call primary

int Highest = MyMax(7, 20);

// call primary

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

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

// call primary

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<<"\n\n";

// call specialization

const char *Var3 = "Class";

const char *Var4 = "Template";

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

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

return 0;

}

 

Output examples:

 

Primary template...

Primary template...

Primary template...

The bigger between 7 and 20 is 20

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

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

Specialization...

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

Press any key to continue . . .

 

 

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