A very simple C++ function template 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++ function template in C++ programming

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




// C++ function template example, the base of class template

#include <iostream>

using namespace std;


// function template declaration and definition

template <class any_data_type>

any_data_type MyMax(any_data_type Var1, any_data_type Var2)


return Var1> Var2 ? Var1:Var2;



int main(void)


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;


// some logical error here?

cout<<"\nLogical error, comparing pointers instead of string..."<<endl;

char* p = "Function";

char* q = "Template";

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

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

cout<<"MyMax(\"Function\",\"Template\") = "<<MyMax(p,q)<<endl;

cout<<"Should use Specialization, shown later..."<<endl;

return 0;



Output examples:


MyMax(10,20) = 20

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

MyMax(1.234,2.345) = 2.345

Logical error, comparing pointers instead of string...

Address of *p = 0012FF60

Address of *q = 0012FF54

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

Should use Specialization, shown later...

Press any key to continue . . .



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