Templates
Contents
Non-Type Template Parameter
A non-type parameter is like a regular parameter with a type and a variable. This can be assigned a value when invoking the template function.File:: template3.cpp
#include <iostream> #include <string.h> using namespace std; template <class T, class Y> void console (T a1, Y b1) { cout << a1 << " " << b1 << endl ; } template <class T, class Y, int i1> void console (T a1, Y b1) { cout << a1 << " " << b1 << " " << i1 << endl ; } int main () { int i1=5 ; string str1 = "demo" ; console( 5, str1 ) ; console<int, string, 10>( 5, str1 ) ; return 0; }
ajay.mittal@USEUG-57MJ2J3 ~/cplus $ g++ template3.cpp ; ./a.exe 5 demo 5 demo 10The above program shows that we can pass more than 1 class parameter into the function. We can also choose to define the type in the template parameters and then give a constant value for it that we can access later on. The "console( 5, str1 ) ;" calls the template function and the types in the template function are deduced to be "int" and "string" .
We can overload the template functions with normal functions.
File:: template4.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); } int GetMax (int a1, int b1) { int result; result = (a1>b1)? a1 : b1 ; cout << "Inside the normal 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; }The normal function will get called if the arguments match and if not then the template function will be called.
File:: template5.cpp
#include <iostream> using namespace std; template <class T , class Y=int> T GetMax (T a1, Y b1) { T result; result = (a1>b1)? a1 : b1 ; return (result); } int main () { int i1=5, j1=6, k1; long l1=10, m1=5, n1; k1 = GetMax<int>(i1, j1 ); n1 = GetMax<long,long>(l1, m1 ); cout << k1 << endl; cout << n1 << endl; return 0; }Normal functions can have default argument values and similarly template functions parameters can have default values as the above example shows.