- //////////////////////////////////////////////////////////////////////////////
- function template
- #include <iostream>
- using namespace std;
- template<class T>
- T add(T &a,T &b)
- {
- T result = a+b;
- return result;
- }
- int main()
- {
- int i =2;
- int j =3;
- float m = 2.3;
- float n = 1.2;
- cout<<"Addition of i and j is :"<<add(i,j);
- cout<<'\n';
- cout<<"Addition of m and n is :"<<add(m
- ,n);
- return 0;
- }
- //////////////////////////////////////////////////////////////////////////////
- #include <iostream>
- using namespace std;
- // This is a function template.
- template <class X> void swapargs(X &a, X &b)
- {
- X temp;
- temp = a;
- a = b;
- b = temp;
- }
- int main()
- {
- int i=10, j=20;
- double x=10.1, y=23.3;
- char a='x', b='z';
- cout << "Original i, j: " << i << ' ' << j << '\n';
- cout << "Original x, y: " << x << ' ' << y << '\n';
- cout << "Original a, b: " << a << ' ' << b << '\n';
- swapargs(i, j); // swap integers
- swapargs(x, y); // swap floats
- swapargs(a, b); // swap chars
- cout << "Swapped i, j: " << i << ' ' << j << '\n';
- cout << "Swapped x, y: " << x << ' ' << y <<
- '\n';
- cout << "Swapped a, b: " << a << ' ' << b <<
- '\n';
- return 0;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////
- =============================================================================================
- function with two genric types
- #include <iostream>
- using namespace std;
- template <class type1, class type2>
- void myfunc(type1 x, type2 y)
- {
- cout << x << ' ' << y << '\n';
- }
- int main()
- {
- myfunc(10, "I like C++");
- myfunc(98.6, 19);
- return 0;
- }
- ================================================================================================================
- Explicitly Overloading a Generic Function
- // Overriding a template function.
- #include <iostream>
- using namespace std;
- template <class X> void swapargs(X &a, X &b)
- {
- X temp;
- temp = a;
- a = b;
- b = temp;
- cout << "Inside template swapargs.\n";
- }
- // This overrides the generic version
- //of swapargs() for ints.
- void swapargs(int &a, int &b)
- {
- int temp;
- temp = a;
- a = b;
- b = temp;
- cout << "Inside swapargs int
- specialization.\n";
- }
- int main()
- {
- int i=10, j=20;
- double x=10.1, y=23.3;
- char a='x', b='z';
- cout << "Original i, j: " << i << ' ' << j << '\n';
- cout << "Original x, y: " << x << ' ' << y << '\n';
- cout << "Original a, b: " << a << ' ' << b <<'\n';
- swapargs(i, j); // calls explicitly overloaded swapargs()
- swapargs(x, y); // calls generic swapargs()
- swapargs(a, b); // calls generic swapargs()
- cout << "Swapped i, j: " << i << ' ' << j << '\n';
- cout << "Swapped x, y: " << x << ' ' << y << '\n';
- cout << "Swapped a, b: " << a << ' ' << b << '\n';
- return 0;
- }
- ========================================================================================================
- Overloading a Function Template
- // Overload a function template
- declaration.
- #include <iostream>
- using namespace std;
- // First version of f() template.
- template <class X>
- void f(X a)
- {
- cout << "Inside f(X a)\n";
- }
- // Second version of f() template.
- template <class X, class Y> void f(X a, Y b)
- {
- cout << "Inside f(X a, Y b)\n";
- }
- int main()
- {
- f(10);
- // calls f(X)
- f(10, 20); // calls f(X, Y)
- return 0;
- }
- /========================================================================================
- #include <iostream>
- #include <cmath>
- using namespace std;
- void myfunc(int i)
- {
- cout << "value is: " << i << "\n";
- }
- void myfunc(double d)
- {
- double intpart;
- double fracpart;
- fracpart = modf(d, &intpart);
- cout << "Fractional part: " << fracpart;
- cout << "\n";
- cout << "Integer part: " << intpart;
- }
- int main()
- {
- myfunc(1);
- myfunc(12.2);
- return 0;
- }
- Consider the overloaded functions in the following example program.
- These functions could not be replaced by
- a generic function because they do not do
- the same thing.
- ========================================================================================================
- template <class myType>
- myType max1(myType a, myType b)
- { return (a>b?a:b); }
- char* max1(char *a, char *b)
- { if(strcmp(a,b)>0)
- return a;
- else
- return b; }
- Void main()
- { cout<<max1(6,10);
- Char s1[20],s2[25];
- cout<<max1(s1,s2);
- }
- ======================================================================================================================
- Multiple Arguments Function
- Templates
- #include <iostream>
- #include <cstring>
- using namespace std;
- template <class T1, class T2, class T3>
- void reverse(T1 x1, T2 x2, T3 x3 )
- {
- cout<<"original sequence"<<" "<<x1<<" "<<x2<<" "<<x3<<endl;
- cout<<"reverse sequence"<<" "<<x3<<" "<<x2<<" "<<x1<<endl;
- }
- int main()
- {
- reverse(12, 34, 86);
- reverse("JIIT","Best","university");
- return 0;}
- ========================================================================================================================
- Member functions of Template class
- A member function of a template class is implicitly treated as a
- template function and it can have template arguments which are same
- as its class template arguments.
- template <class T>
- class temp_stack
- { void push(T a);
- };
- When defined outside:
- template <class T>
- Void temp_stack<T>::push(T a)
- {
- }
- ==================================================================================================================
- CLASS TEMPLATE WITH MULTIPLE
- PARAMETERS
- #include <iostream>
- using namespace std;
- template<class T1, class T2>
- class A
- {
- T1 a;
- T2 b;
- public:
- A(T1 x,T2 y)
- {
- a = x;
- b = y;
- }
- void display()
- {
- std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
- }};
- ================================================================================================================
- #include <iostream>
- using namespace std;
- template<class T, int size>
- class A
- {
- public:
- T arr[size];
- void insert()
- {int i =1;
- for (int j=0;j<size;j++)
- {
- arr[j] = i;
- i++;
- }}
- void display()
- {
- for(int i=0;i<size;i++)
- {
- std::cout << arr[i] << " ";
- }}
- };
- int main()
- {
- A<int,10> t1;
- t1.insert();
- t1.display();
- return 0;
- }
- ==========================================================================================================================
- For Example, consider we have a template class ‘myIncrement’ which has a constructor to initialize a value and a template function toIncrement that increments the value by 1.
- This particular class will work perfectly for all the data types except for char. Instead of incrementing the value for char, why not give it a special behavior and convert the character to uppercase instead?
- In order to do this, we can go for template specialization for the char data type.
- This implementation is shown in the below code Exampl#include <iostream>
- am>
- using namespace std// class template:
- te:
- template <class T>
- class myIncrement {
- T value;
- public:
- myIncrement (T arg) {value=arg;}
- T toIncrement () {return ++value;}// class template specialization:
- on:
- template <>
- class myIncrement <char> {
- char value;
- public:
- myIncrement (char arg) {value=arg;}
- char uppercase ()
- {
- if ((value>='a')&&(value<='z'))
- value+='a'-'a';
- return value;
- }
- };
- int main () {
- myIncrement<int> myint (7);
- myIncrement<char> mychar ('s');
- myIncrement<double> mydouble(11.0);
- cout<<"Incremented int value: "<< myint.toIncrement()<< endl;
- cout<<"Uppercase value: "<<mychar.uppercase()<< endl;
- cout<<"Incremented double value: "<<mydouble.toIncrement()<< endl;
- return 0;
- }
- //////////////////////////////////////////////////////////////////////////////////=====
- ===
- =====================================================================================
- ht//vulms.vu.edu.pk/Courses/CS304/Downloads/CS304_Handouts%20(Updated).pdf
- pdf
- ht//quizxp.com/programming-in-c-plus-plus/
- us/
- ======================================================================================
- / Min/Max Templa#include<iostream>
- #include <string>
- ng>
- using namespace std// Template for the min function
- ion
- template <class T>
- T min(T number1, T number2)
- {
- return (number1 < number2)? number1 : number2;
- // Template for the max function
- ion
- template <class T>
- T max(T number1, T number2)
- {
- return (number1 > number2)? number1 : number2;
- // The main function
- ion
- int main()
- {// Test min and max with int arguments.
- ts.
- int num1 = 5;
- int num2 = 3;
- cout << "minimum of 5, 3 is: " ;
- cout << min(num1, num2) << endl;
- cout << "maximum of 5, 3 is: " ;
- cout << max(num1, num2) << endl;
- // Test min and max with double arguments.
- ts.
- double num3 = 5.5;
- double num4 = 3.5;
- cout << "minimum of 5.5, 3.5 is: " ;
- cout << min(num3, num4) << endl;
- cout << "maximum of 5.5, 3.5 is: " ;
- cout << max(num3, num4) << endl;
- // Test min and max with string arguments.
- ts.
- string hello = "hello";
- string hi = "hi";
- cout << "minimum of \"hello\" and \" is: "s: ";
- cout << min(hello, hi) << endl;
- cout << "maximum of \"hello\" and \" is: "s: ";
- cout << max(hello, hi) << endl;
- return 0;
- }
- ====================================================================================================================
- ================================================
- ====================================================================
- ==================================================// A Generic bubble sort.
- #include <iostream>
- am>
- using namespace std;
- template <class X> void bubble(
- X *ite// pointer to array to be sorted
- ted
- int cou// number of items in array
- ray
- {
- register int a, b;
- X t;
- for(a=1; a<count; a++)
- for(b=count-1; b>=a; b--)
- if(items[b-1] > items[b]// exchange elements
- nts
- t = items[b-1];
- items[b-1] = items[b];
- items[b] = t;
- }
- }
- int main()
- {
- int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
- double darray[5] = {4.3, 2.5, -0.9, 100.2, 3.0};
- int i;
- cout << "Here is unsorted integer array: ";
- for(i=0; i<7; i++)
- cout << iarray[i] << ' ';
- cout << endl;
- cout << "Here is unsorted double array: ";
- for(i=0; i<5; i++)
- cout << darray[i] << ' ';
- cout << endl;
- bubble(iarray, 7);
- bubble(darray, 5);
- cout << "Here is sorted integer array: ";
- for(i=0; i<7; i++)
- cout << iarray[i] << ' ';
- cout << endl;
- cout << "Here is sorted double array: ";
- for(i=0; i<5; i++)
- cout << darray[i] << ' ';
- cout << endl;
- return 0;
- }
- ======================================================================================================================
- ==================== compacting an array
- ================================================================================
- // A Generic array compaction function.
- #include <iostream>
- am>
- using namespace std;
- template <class X> void compact(
- X *ite// pointer to array to be compacted
- ted
- int cou// number of items in array
- ray
- int sta// starting index of compacted region
- ion
- int e// ending index of compacted region
- ion
- {
- register int i;
- for(i=end+1; i<count; i++, start++)
- items[start] = items[/* For the sake of illustration, the remainder of
- the array will be zeroed. */. */
- for( ; start<count; start++) items[start] = (X) 0;
- }
- int main()
- {
- int nums[7] = {0, 1, 2, 3, 4, 5, 6};
- char str[18] = "Generic Functions";
- int i;
- cout << "Here is uncompacted integer array: ";
- for(i=0; i<7; i++)
- cout << nums[i] << ' ';
- cout << endl;
- cout << "Here is uncompacted string: ";
- for(i=0; i<18; i++)
- Chapter 18: Templates 471 C++
- cout << str[i] << ' ';
- cout << endl;
- compact(nums, 7, 2, 4);
- compact(str, 18, 6, 10);
- cout << "Here is compacted integer array: ";
- for(i=0; i<7; i++)
- cout << nums[i] << ' ';
- cout << endl;
- cout << "Here is compacted string: ";
- for(i=0; i<18; i++)
- cout << str[i] << ' ';
- cout << endl;
- return 0;
- }
- ======================================================================================================================
- ==========================================
- stackssss
- // This function demonstrates a generic stack.
- #include <iostream>
- am>
- using namespace std;
- const int SIZE = // Create a generic stack class
- ass
- template <class StackType> class stack {
- StackType stck[SIZ// holds the stack
- ack
- int t// index of top-of-stack
- ack
- public:
- stack() { tos = 0// initialize stack
- ack
- void push(StackType o// push object on stack
- ack
- 474 C++: The Complete Reference
- StackType pop// pop object from stack
- ack// Push an object.
- ct.
- template <class StackType> void stack<StackType>::push(StackType ob)
- {
- if(tos==SIZE) {
- cout << "Stack is full.\n";
- return;
- }
- stck[tos] = ob;
- tos++// Pop an object.
- ct.
- template <class StackType> StackType stack<StackType>::pop()
- {
- if(tos==0) {
- cout << "Stack is empty.\n";
- return// return null on empty stack
- ack
- }
- tos--;
- return stck[tos];
- }
- int main(// Demonstrate character stacks.
- ks.
- stack<char> s1, // create two character stacks
- cks
- int i;
- s1.push('a');
- s2.push('x');
- s1.push('b');
- s2.push('y');
- s1.push('c');
- s2.push('z');
- for(i=0; i<3; i++) cout << "Pop s1: " << s1.pop() << "\n";
- for(i=0; i<3; i++) cout << "Pop s2: " << s2.pop() << "\// demonstrate double stacks
- cks
- stack<double> ds1, d// create two double stacks
- cks
- Chapter 18: Templates 475 C++
- ds1.push(1.1);
- ds2.push(2.2);
- ds1.push(3.3);
- ds2.push(4.4);
- ds1.push(5.5);
- ds2.push(6.6);
- for(i=0; i<3; i++) cout << "Pop ds1: " << ds1.pop() << "\n";
- for(i=0; i<3; i++) cout << "Pop ds2: " << ds2.pop() << "\n";
- return 0;
- }
- ============================================================================================================================
- =================================================genric safe array
- =======================================================================// A generic safe array example.
- #include <iostream>
- #include <cstdlib>
- ib>
- using namespace std;
- const int SIZE = 10;
- template <class AType> class atype {
- AType a[SIZE];
- public:
- atype() {
- register int i;
- for(i=0; i<SIZE; i++) a[i] = i;
- }
- AType &operator[](int i);// Provide range checking for atype.
- pe.
- template <class AType> AType &atype<AType>::operator[](int i)
- {
- if(i<0 || i> SIZE-1) {
- cout << "\nIndex value of ";
- cout << i << " is out-of-bounds.\n";
- exit(1);
- }
- return a[i];
- }
- int main()
- {
- atype<int> int// integer array
- ray
- atype<double> double// double array
- ray
- int i;
- cout << "Integer array: ";
- for(i=0; i<SIZE; i++) intob[i] = i;
- for(i=0; i<SIZE; i++) cout << intob[i] << " ";
- cout << '\n';
- cout << "Double array: ";
- for(i=0; i<SIZE; i++) doubleob[i] = (double) i/3;
- for(i=0; i<SIZE; i++) cout << doubleob[i] << " ";
- cout << '\n';
- intob[12] = 1// generates runtime error
- ror
- return 0;
- }
- ===========================================================================================================================
- =============================================================
- template <class T>
- class Complx {
- private:
- T real, imag;
- public:
- Complx(T&, T&);
- T& getReal();
- T& getImag();
- };
- template <class T>
- Complx<T>::Complx(T& a, T& b) {
- real = a;
- imag = b;
- }
- template <class T>
- T& Complx<T>::getReal() {
- return real;
- }
- template <class T>
- T& Complx<T>::getImag() {
- return imag;#include <iostream>
- am>
- int main()
- {
- double i=100, j=200;
- Complx <double> myComplx(i,j);
- std::cout <<"My complex is " << myComplx.getReal() << ","
- << myComplx.getImag() << std::endl;
- }
- ============================================================================================================================
- =============================================================================
- // Demonstrate non-type template arguments.
- #include <iostream>
- #include <cstdlib>
- ib>
- using namespace s// Here, int size is a non-type argument.
- nt.
- template <class AType, int size> class atype {
- AType a[siz// length of array is passed in size
- ize
- public:
- atype() {
- register int i;
- for(i=0; i<size; i++) a[i] = i;
- }
- AType &operator[](int i);// Provide range checking for atype.
- pe.
- template <class AType, int size>
- AType &atype<AType, size>::operator[](int i)
- {
- if(i<0 || i> size-1) {
- cout << "\nIndex value of ";
- cout << i << " is out-of-bounds.\n";
- exit(1);
- }
- return a[i];
- }
- int main()
- {
- atype<int, 10> int// integer array of size 10
- 10
- atype<double, 15> double// double array of size 15
- 15
- int i;
- cout << "Integer array: ";
- for(i=0; i<10; i++) intob[i] = i;
- for(i=0; i<10; i++) cout << intob[i] << " ";
- cout << '\n';
- cout << "Double array: ";
- for(i=0; i<15; i++) doubleob[i] = (double) i/3;
- for(i=0; i<15; i++) cout << doubleob[i] << " ";
- cout << '\n';
- intob[12] = 1// generates runtime error
- ror
- return 0;
- }
- ====================================================================================================================
- template <> wala haiyeh
- // Demonstrate class specialization.
- #include <iostream>
- am>
- using namespace std;
- template <class T> class myclass {
- T x;
- public:
- myclass(T a) {
- cout << "Inside generic myclass\n";
- x = a;
- }
- T getx() { return x; }// Explicit specialization for int.
- nt.
- template <> class myclass<int> {
- int x;
- public:
- myclass(int a) {
- cout << "Inside myclass<int> specialization\n";
- x = a * a;
- }
- int getx() { return x; }
- };
- int main()
- {
- myclass<double> d(10.1);
- cout << "double: " << d.getx() << "\n\n";
- myclass<int> i(5);
- cout << "int: " << i.getx() << "\n";
- return