Acknowledgement
Acknowledgement
Acknowledgement
Acknowledgement
Thanking you,
Neha
Chavan [SYBscIT-18]
& Nishant
Nair [SYBscIT-84]
3
Viva College of Arts, Commerce
and Science.
3
Introduction
3
Generic programming in object-oriented
languages
When creating containers of objects it is possible to write specific
implementations for each datatype contained, even if the code is
virtually identical except for different datatypes. In C++, this
duplication of code can be circumvented by defining a template class:
template<typename T>
class List
{
/* class contents */
};
List<Animal> list_of_animals;
List<Car> list_of_cars;
Above, T is a placeholder for whatever type is specified when the list
is created. These "containers-of-type-T", commonly called generics,
are a generic programming technique allowing a class to be reused
with different datatypes as long as certain contracts such as subtypes
and signature are kept
template<typename T>
void Swap(T & a, T & b) //"&" passes parameters
by reference
{
T temp = b;
b = a;
a = temp;
}
3
cout << hello << world << endl; //Output is
"Hello, world!"
template
Templates are a feature of the C++ programming language that
allow functions and classes to be operate with generic types. This
allows a function or class to work on many different data types
without being rewritten for each one.
Function Template
Function and Function Template
Class Template
3
Template Argument
Class Template
Function template
template<class T>
void swap ( T & x , T & y) // by reference
{
Tt; //template type
temporary variable used in swapping
t = x;
x = y;
y = t;
}
3
Such functions are known as function templates. When swap
operation is requested on operands of any data type, the compiler
creates a function internally without the user intervention and invokes
the same
template
keyword data type
atleast one argument
must be template type
3
normal function and the parameters can be of any data-type. When the
compiler encounters a call to such functions, it identifies the data type
of the parameter and creates a function internally and makes a call to
it. The internally created function is unknown to the user. The
program gswap.cpp makes use of templates and avoids the
overhead of rewriting functions having body of the same pattern, but
operating on different data types.
3
cin >> a >> b;
swap( a, b) ; // compiler creates and calls
swap ( int &x, int&y );
cout << “ On Swapping <a, b>: “ << a <<
“ “ << b << end1;
float c, d;
cout << “ Enter two floats <c, d> : “ ;
cin >> c >> d;
swap( c, d ); // compiler creates and calls swap
( float &x, float &y );
cout << “ On Swapping <c, d>: “ << c <<
“ “ << d;
}
RUN
Enter two character <ch1, ch2 >: R K
On Swapping <ch1, ch2>: K R
Enter two integer <a, b > : 10 5
On Swapping <a, b>: 5 10
Enter two floats <c, d> : 20.5 99.5
On Swapping <c, d>: 99.5 20.5
Function templates are not suitable for handling all data type, and
hence, it is necessary to override function template by using normal
functions for specific data types. When a statement such as
3
max (str1, str2)
is executed, it will not produce the desired result. The above call
compares memory addresses of strings instead of their contents. The
logic for comparing strings is different from comparing integer or
floating-point data type. It requires the function having the definition :
If the program has both the function and function template with the
same name, first, the compiler selects the normal function, if it
matches with the requested data type, otherwise, it creates a function
using a function template. This is illustrated in the program
max2.cpp.maximum of standard and derived data type items
#include<iostream.h>
#include<string.h>
template<class T>
T max(Ta, Tb)
{
If(a>b)
return a;
else
return b;
}
//specifically for string data types
char*max(char*a,char*r)
3
{
if(strcmp(a,b)>0)
return a;
else
return b;
}
void main()
{
//max with character data types
char ch,ch1,ch2;
cout<<”Enter two character <ch1,ch2>:”;
cin>>ch1>>ch2;
ch=max(ch1,ch2);
cout<<”max(ch1,ch2):”<<ch<<end1;
// max with integer data types
int a, b, c;
cout << “ Enter two integer <a, b>: “;
cin >> a >> b;
c = max( a, b);
cout << “max (a, b): “ << c << end1;
// max with string data types
char str1[20], str2[20];
cout << “ Enter two string <str1, str2>: “;
cin >> str1>> str2;
cout << “max (str1, str2): “ << max (str1,
str2);
}
RUN
3
max(ch1,ch2) : Z
Enter two integer <a, b>:
max( a, b): 6
Enter two string <str1, str2>: NEHA NISHANT
max (str1, str2): NEHA
3
cin>>IntNums[i]<<” “;
Bubblesort( IntNums,size );
cout<<”Sorted Vector”<<end1;
for(i=0; i< size; i++)
cout<<IntNums[i]” “;
// Floating point numbers sorted
cout<<”\nEnter the elements of the float
vector…”<max-25>
for( i=0 ; i < size; i++)
cin > > size;
cout<<”Enter the elements of float vector
…”<<end1;
for( i =0 ; i< size ; i++)
cin >>floatnums [i];
Bubblesort ( FloatNums, size );
cout << “ Sorted Vector : “ << end1;
for ( i = 0 ; i < size ; i++)
cout << FloatNums [i] << “ “ ;
}
RUN
Program to sort elements….
Enter the size of the integer vector < max – 25 > :
enter the elements of the integer vector …
8
4
1
6
Sorted Vector :
1 4 6 8
Enter the elements of float vector <max – 25 > : 3
Enter the elements of float vector
3
8.5
3.2
8.9
Sorted vector :
3.2 8.5 8.9
Overload Function Templates
3
{
print( 1 );
print( 1.5 );
print( 520,2 );
print( “OOP is Great”,3 );
}
RUN
1
1.5
520
520
Oop is great
Oop is great
Oop is great
3
{
int x;
double y;
};
template < class T >
void Assign_A ( T a, T b, A & S1 )
{
S1.x = a;
S1.y = b;
}
template < class T >
void Assign_B( T a, T b, A & S2 )
{
S2.x = a;
S2.y = b;
}
void main( void )
{
A S1;
B S2;
void Assign_A( 3, 4, S1);
void Assign_B( 3, 3.1415, S2); //Error : no
match for void Assign_B
( int, double, B)
}
3
processing standard data types as illustrated in the program
student.cpp.
// student.cpp : student record and template
with user defined data types
#include <iostream.h>
struct stuRec
{
char name[30];
int age;
char collegeCode;
};
template <class T >
void Display ( T & t )
{
RUN
Enter the student record details …
Name : NEHA
Age : 19
College Code : A
The student record :
Name : NEHA
3
Age : 19
College Code : A
class Templates
The syntax of declaring class template and defining objects using the
same is shown in figure. The definition of class template implies
defining template data and member functions.
3
{
// data items of template type T1, T2,
……
T1 data1;
………
// functions of template arguments T1,
T2,……….
Void func1 ( T1 a, T2 &b);
…………
T func1 ( T1 *x, T2 *y);
};
The prefix template < class T > specifies that a template is being
declared, and that a type-name T will be used in declaration. In
other words, DataStack is a parameterized class with T as its
generic data type.
3
DataStack < int > stack_int; //stack of
integers datatype to be
substituted for template
datatype
stack_int.push (10);
3
Template Argument
A template can have character strings, function names, and
constant expressions in addition to template type arguments. Consider
the following class template to illustrate, how the compiler handles
the creation of objects using class template
class myclass
{
Float arr [10] ;
};
Again is a statement such as,
myclass <int, 5> new2;
is encountered for creating the object new2, the compiler creates the
following class:
3
class myclass
{
int arr [5];
};
3
public:
Stack20 ( ) { top = 0; }
void Push ( const T & elem ) { Array
[ top++ ] = elem }
T Pop ( void ) { return Array [ --top ]; }
int GetSize ( void ) const { return top
+1}
T & GetTop (void ) {return Array [top];}
};
The declaration of the class template StackN is preceded by,
template < class T, unsigned SIZE >
3
Inheritance of class template
3
//template type data and functions
data type for template in
};
base class
template < class T1,………>
Class DerivedClass : public BaseClass < T1,
……..>
{
//template type data type and functions
};
Syntax for inheriting template base class
The class deriving a template type base class can be a normal class
or a class-template. If a new derived class is a normal class, the data
type of template argument to the base class must be specified at the
point of derivation. Otherwise, template arguments type specified at
the point of instantiation of a class template can also be passed.
Consider an example of declaring the template class Vector . It
inherits all the properties from the base template class sVector .
The derived template class Vector is still a static vector containing
twenty elements. Member functions that perform insert, delete and
search are added to the derived class. The member function have the
prefix <template class T >, since the derived class operates
on the undeclared type T. The specification of a new template class
created by inheriting another template-based base class is given
below:
<template class T >
Class Vector : public sVector < T >
{
…….
read( );
…….
};
3
The member functions defined with its class body have the same
syntax as member of non-template-type classes. However , member
function defines outside the body of a class, for instance, has the
following specification:
<template class T >
void Vector < T > : : read ( )
{
……// body of the read ( )
}
Note that, the member functions of a class-template are treated as
function-template type members. The class Vector can be
instantiated as follows:
Vector < int > v1;
In case, the int specified in angular brackets in first assigned to
generic data type in the Vector class and then the same is also passed
to its base class.
A derived class of a template based base class is not
necessarily template derived class. That is, the non-
template-based derived classes can also be created from the template
based base classes. In this case, the undefined template argument T
has to be specified during derivation, for instance, as follows:
class Vector : public sVector < int >
{
……..
};
It creates a new class called Vector from the template-based base
class sVector . The int is passed as the template argument type to
the base class.
3
The class template can also be declared for a class having
operator overloaded member functions. The syntax for declaring
operator overloaded functions is the same as class template members
and overloaded functions. The class template with operator
overloading will allow to truly extend the language and at the same
time retaining the readability of object manipulating code. The
program complex.cpp illustrates the overloading of the +operator in
the class template complex. In this case, the members of the complex
number ( real and imaginary ) can be any of the standard data types.
3
cin >> real ;
cout << “Imag Part ? “ ;
cin >> imag ;
}
complex operator + ( complex
c2 ); // complex addition
void outdata ( char * msg ) //
display complex number
{
cout << msg << “ ( “ << real ;
cout << “ , “ << imag << “ ) “ <<
end1;
}
};
template<class T>
complex <T> complex< T > : : operator +
( complex < T > c2 );
{
complex < T > temp; // object
temp of complex class
3
complex < int > c1, c2, c3; // integer
complex objects
cout << “Addition of integer complex
objects…..” << end1;
cout << “Enter complex number c1 ….”
<< end1;
c1.getdata( );
cout << “Enter complex number c2 ….”
<< end1;
c2.getdata( );
c3 = c1 +c2; //integer
addition
c3.outdata ( “c3 = c1 +c2: “ ) ; // display
result
complex < float > c4, c5, c6; // integer
complex objects
cout << “Addition of float complex
objects…..” << end1;
cout << “Enter complex number c4 ….”
<< end1;
c4.getdata( );
cout << “Enter complex number c5 ….”
<< end1;
c5.getdata( );
c6 = c4 +c5 ; // floating
addition
c6.outdata ( “c6 = c4 +c5: “ ) ; // display
result
}
RUN
3
Addition of integer complex objects…..
Enter complex number c1 …
Real Part ? 1
Imag Part ? 2
Enter complex number c2 …
Real Part ? 3
Imag Part ? 4
c3 = c1 +c2: ( 4, 6)
Addition of float complex objects…
Enter complex number c4 …
Real Part ? 1.5
Imag Part ? 2.5
Enter complex number c5 …
Real Part ? 2.4
Imag Part ? 3.7
c6 = c4 +c5: ( 3.9, 6.2 )