Templates
Contents
Function Template Specialization
We defined a template function for general types but we want the function to behave differently for a particular type. We write a similar function with that type. This is known as Function Template Specialization.File:: function1.cpp
#include <iostream> using namespace std; template <class T> T GetMax (T a1, T b1) { T result; result = (a1>b1)? a1 : b1 ; cout << "Inside the template function." << endl ; return (result); } template <> int GetMax<int> (int a1, int b1) { int result; result = (a1>b1)? a1 : b1 ; cout << "Inside the int function." << endl ; return (result); } int main () { int i1=5, j1=6, k1; long l1=10, m1=5, n1; k1 = GetMax(i1, j1 ); n1 = GetMax(l1, m1 ); cout << k1 << endl; cout << n1 << endl; return 0; } $ g++ function1.cpp ; ./a.exe Inside the int function. Inside the template function. 6 10We can also add in a normal functions in addition to template specialization functions.
File:: function2.cpp
#include <iostream> using namespace std; template <class T> T GetMax (T a1, T b1) { T result; result = (a1>b1)? a1 : b1 ; cout << "Inside the template function." << endl ; return (result); } template <> int GetMax<int> (int a1, int b1) { int result; result = (a1>b1)? a1 : b1 ; cout << "Inside the int function." << endl ; return (result); } int GetMax (int a1, int b1) { int result; result = (a1>b1)? a1 : b1 ; cout << "Inside the overloaded function." << endl ; return (result); } int main () { int i1=5, j1=6, k1; long l1=10, m1=5, n1; k1 = GetMax(i1, j1 ); n1 = GetMax(l1, m1 ); cout << k1 << endl; cout << n1 << endl; return 0; } $ g++ function2.cpp ; ./a.exe Inside the overloaded function. Inside the template function. 6 10The compiler will consider the non-template function first to see if there is a match before moving on to template functions.
File:: template_ex1.cpp
#include <iostream> using namespace std; //TO DO //Write a template function called Add // that takes 2 arguments of the same type // and returns a result using the "+" operator int main () { int i1=5, j1=6 ; string str1 = "Charles " ; string str2 = "Babbage" ; cout << Add(i1, j1) << endl; cout << Add(str1, str2) << endl; return 0; }