0% found this document useful (0 votes)
12 views30 pages

Template and Namespace

Template and namespace of C++ Programming

Uploaded by

bikash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views30 pages

Template and Namespace

Template and namespace of C++ Programming

Uploaded by

bikash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Template and Namespace

Kashiram Pokharel
Templates:
• It is a new feature added to c++ that enable to create generic (or general) classes and
functions and thus supports for generic programming.
• Generic programming means, using the general classes and functions for the several types of
classes and functions. It is used for data type generalization.
• For example using a function for calculation and returning the sum of two numbers, both
integer type and floating point type.
• Generally, the function i.e. designed to operate on one data type can’t be used to operate on
another data type. A function template or generic function can be used to operate on
different type of data by taking data type as a parameter.
• Through a template function single general procedure can be applied to a wide variety of data
.i.e. with template single algorithm of data i.e. with template, single algorithm can be used for
different data type.
• A template can be used to create a family of classes and functions. So, there are two types of
template.
• function template;
• class template.
Function template:
• A function template is method for creating a single function for a family
of similar functions in a generic manner. For example, we can define a
template function say mul() function, which applies for multiplication
of all int, float and double type values.
• Syntax:
template<class T>
return type function name(argument of type T)
{
..................
.................
}
Function template:
• We can use more than one template parameter in the function template definition as
follows
template<class T1, class T2>
Void display(T1 a)
{
…………….
T2 x;
……….
}
To call this function
int x;
display(x); // which gives error because I can’t replace the T2 with appropriate data
type.
To solve this situation function initialization is done explicitly as
int x;
display<float>(x); // here T1 is type x and T2 is type float.
program to multiply two set of values; first set an integer values and
second set floating point values using function using function templates
int main()
#include <iostream> {
using namespace std; int a,b;
template<class T>
T mul(T a,T b) float x,y;
{ cout<<"enter two integer values";
T c; cin>>a>>b;
c=a*b;
return(c); cout<<"enter two floating point values";
} cin>>x>>y;
cout<<"product of two integer="<<mul(a,b);
cout<<"product of two floating points="<<mul(x,y);
return 0;
}
Program to swap two sets of values first set an integer values
and second set a floating point values using function templates
void main()
template<class T> {
int m,n;
void swap(T &a,T &b) float x.y;
{ cout<<”enter two integer values=”;
cin>>m>>n;
T temp; cout<<”enter two floating point values=”;
temp=a ; cin>>x>>y;
a=b; cout<<”Integer before swapping :”<<m<<”\t”<<n;
cout<<”floating point before swapping”<<x<<”\t”<<y;
b=temp; swap(m,n);
} swap(x,y);
cout<<”integer after swapping =”<<m<<”\t”<<n;
cout<<”floating point after swapping=”<<x<<”\t”<<y;
}
int main()
{
Sorting array: int m,n,x[10],i;
float y[10];
cout<<"how many integer to sort:"<<endl;
cin>>m;
#include <iostream> cout<<"how many floating point to sort:";
using namespace std; cin>>n;
template <class T> for(i=0;i<m;i++)
int sort(int n,T a[]) {
{ cout<<"enter number"<<i+1<<"=";
int i,j; cin>>x[i];
for(i=0;i<n-1;i++) }
{ cout<<"enter floating point value"<<endl;
for(j=i+1;j<n;j++) for(i=0;i<n;i++)
{ {
if(a[i]<a[j]) cout<<"enter number "<<i+1<<"=";
{ cin>>y[i];
swap(a[i],a[j]); }
} sort(m,x);
} sort(n,y);
} cout<<"sorted integer"<<endl;
} for(i=0;i<m;i++)
template<class T> cout<<x[i]<<endl;
void swap( T &a,T &b) cout<<"sorted floating point";
{ for(i=0;i<m;i++)
T temp; {
temp=a; cout<<y[i]<<"\t";
a=b; }
b=temp; }
}
Function template with multiple parameters:

#include <iostream> int main()


{
using namespace std; display<int,string>(100,"ram");
display<char,int>('A',123);
template<class T1,class T2> display(1.234,12);
void display(T1 x,T2 y) return 0;
{ }
cout<<"x="<<x<<"\t"<<"y="<<y <<endl;
}
overloading of function template:
1. overloading with normal function:
• When we are defining both template function and normal function of
same name with exactly same name with exactly matching
parameters in the same scope then compiler selects the more specific
function.
• If normal function is an exact match than function template, then the
normal function is selected.
• First an ordinary function that has an exact match is called.
• Then, a template function with exact match will call.
Consider the following function:
template <class t>
T max (T a,T b)
{
T result ; int main()
if(a>b)
result=a; {
else int x=10,y=20;
result=b;
} cout<<max(x,y);
char * max(char *a, char *b) char str1[ ]=”hello”;
{
char *c; char str2[ ]=”hi”;
if(strcmp(a,b)>0) cout<<max(str1,str2);
{
c=a; return 0;
}
else }
c=b;
return c;
}
#include <iostream>
2. Overloading with another using namespace std;

template function: template <class T>


void display(T a,T b)
{
• If the argument supplied are of cout<< "value of a="<<a;
cout<< "value of b="<<b;
same type then function template
}
that take argument of same type is
template<class T1,class T2>
called. void display(T1 a,T2 b)
• If argument supplied are of different {
types then the function template cout<< "In second case value of a="<<a;
that take different argument is cout<< "In second case value of b="<<b;
called }
int main()
{
display(2,3);
display(1.5,10) ;
return 0;
Class template:
• A function generated from a function template is known as template
function. Similarly a class created from a class template is known as template
class. A class template is a method of creation of creation of single class to
operate on different type of variable. A class that operates on any type of
data is called class template.Declaring class templates is similar to declaring
function templates: Before the declaration, a statement declares an identifier
as a type parameter. Again, T is usually used as an identifier:
template <typename T> Example:
class class_name template <class T>
{ class Stack
{


};
};
Here, again, the keyword class can be used instead of typename:
Class template:
• A class template is just like an ordinary class definition except the prefix
template<class T>and the use of type T. This prefix tells the compiler that a
template is going to be declared and ‘T’ is used as a type name in
declaration. ’T’ may be substituted by any data type including the user
defined types. The syntax for class template is
template<class T>
class class_name
{
.......................
.......................
};
Program to multiply two sets of numbers using
class templates: template<class T>
void mul<T>::display()
template<class T> {
T e;
class mul e=a*b;
{ cout<<”product=”<<e;
private: }
T a,b; void main()
public: {
void getinfo(); mul<int> obj1;
void display(); mul<float>obj2;
}; cout<<”enter integers”;
template<class T> obj1.getinfo();
cout<<”enter floatinf points”;
void mul<T>::getinfo() obj2.getinfo();
{ cout<<”for integer”;
cout<<”enter numbers=”; obj1.display(();
cin>>a>>b; cout<<”for floating points”;
} obj2.display();
}
example
Multiple generic types in class template: Template<class T1,class T2>
class sample
Or {

Class template with multiple parameters: T1 a;


T2 b;
Syntax: public:
template<class T1,class T2,..............> sample(T1 x,T2 y){
class class_name; a=x;
{ b=y;
............... }
........... void show(){
}; cout<<”a=”<<a<<endl;
If there are two generic types in class template, then, cout<<”b=”<<b<<endl;
syntax: }};
template<class T1,class T2> void main()
class class_name {
{ sample obj1(10,12.20);
..................... sample(‘A’,123);
................ obj1.show();
}; obj2.show();
}
Default Argument with class template:
• The class template has a default argument associated with template parameter which
defines the type name of template to be used when template argument is not
specified while creating instance of a class.
• The template class argument is specified in the class declaration in the following form.
template <class template_type=default_datatype>
class class_name
{
…………
…………
};
Where template_type=template parameter for generic datatype.
Example:
Template<class T=float>
Class demo
{
………..
………..
};
Default Argument with class template:

• When creating instance of class demo, when the argument type is not supplied then
float type will be assumed .but if argument type is supplied then supplied type is
assumed
• For example:
Demo <int >obj; //template argument is int
Demo < > obj1; //template argument is float when not supplied.
The class template can have a default argument associated with template parameter.
The syntax is
Template <class template_type=default data_type>
Class class_name
{
……..
};
Where template type is the template parameter for generic data type
Default data_type is the type name to be used when template type is not specified
Non template type argument:

• If class template contains the non template type argument then the
value of non template type must be known at compile time, for this
we have to give the value of non template type argument while
creating the instance of a class.
template<class T,int size>
T test<T,size>::max()
{
T m;
using namespace std; m=arr[0];
for(int i=0;i<size;i++)
template<class T, int size> {
class test if(arr[i]>m)
{
{ m=arr[i];
}
int arr[size]; }
public: return m;
}
void initialize();
template<class T,int size>
T max(); void test<T,size>::minimum()
void minimum(); {
cout<<"find minimum your self";
};
template<class T,int size> }
void test<T,size>::initialize() int main()
{ {
for(int i=0;i<size;i++) test<int,7> obj;
{ cout<<"enter array element";
cout<<"enter array element for index "<<i<<" = "; obj.initialize();
cin>>arr[i]; cout<<"Greater number="<<obj.max();
} cout << "Hello world!" << endl;
} return 0;
Derived class Template:
• The derived class can be created in the following ways:
• From template base class to non template derived class
• From template base class to template derived class (Having same template
parameter as in base)
• From template base class to template derived class (Having different
template parameter as in base)
• Non template base class to template derived class.
• When creating the non template class or a template class from the base
class template, The template argument of the base class can be supplied
during the inheritance process, This replaces the template parameter of
the base class template with the type supplied as argument during the
inheritance and eliminate the template parameter of the base class in the
derived class.
class second: public first<int>
{
float y;
Example: public:
second()
#include <iostream> {
using namespace std; y=0.0;
template<class T> }
class first second(float b):first<int>(5)
{ {
protected: y=b;
T x; }
public: void display1()
first() {
{ cout<<"value of y="<<y;
x=0; cout<<"value of x="<<x;
} }
first(T a) };
{ int main()
x=a;
} {
void display() second obj(10.3);
{
cout<<"Base class x="<<x; obj.display1();
} return 0;
};
standard templates library(STL)
• We are created generic class and function using template to support
generic programming.
• Alexander Stephan and menglee developed a set of general purpose
classes and functions using templates that put serve as a standard for
storing and processing a data .
• The collection of these generic classes and functions is called standard
template library (STL).
• The use of STL can save considerable time and effort, and thus lead to
high quality programs these are the benefits of STL, as we are basically
“reusing” the well written and well tested components defined in the stl
Components of stl:

• The components of STL are now part of the standard c++ library, and
these are defined in the namespace std. This is why; we use the “using
namespace” directive to inform the compiler that we are using the
standard++ library.
• Three core components of STL are
-containers
-algorithms
-iterators.
-Function
All these component work together so, as to provide support for better
programming.
• A container is an object that stores data .it is a way how the data are
organised in memory some examples of containers are stack, queue, list, array
etc.
• An algorithm is a procedure i.e. used to process the data contained in the
containers.
• Algorithms act on container data with some predefined functions, wherein
data gets changed for better results, and provide a smooth way for further
manipulation.
• An iterators is an object that connect algorithm with containers. It actually
points to an elements in the container, so it is treated just like a pointer
• Iterators are the “smart pointers” that point to the data in the container like
pointers do
• Functors are “function objects” that are passed as arguments and point to
those functions that are to be executed.
• Functors are mostly used to handle events.
Container class
• If an object of one class is the class class3
member of another class, then that {
class (second one) is called the private:
container class, then that class1 obj1;
class(second one) is called the class2 obj2;
container class. public:
class class1 ..............
{ ..............
........... };
............... void main()
}; {
class class2 class obj3;
{ ....................
............
............ ...................
}; }
here class3 is the container class.
namespace
• In c++ program, we define variables and function as in different scopes
(private or public).A new keyword “namespace” is add in ANSI c++
standard library to define a new scope that holds global identifiers.
• An example of namespace is the standard c++ library named std in which
all classes and function as well as templates are declared i.e. why we use
the following directive in our program.
Using namespace std;
• The above statement specifies that the members defined in std namespace
will be frequently used throughout the program .The definition of our own
namespace scope in programs certain name conflicts situation.
Defining a namespace: void display(int n)
{
• The syntax for defining a name space is
similar to that for defining a class, with cout<< “n=”<<n ;
only the difference that the namespace }
definition donot have terminating
semicolon.
void main( )
namespace namespace_name
{
{
using namespace name ; // using directive
//declaration of variables, function,class etc;
cout<< “m=”<<m<<endl ;
} display(22) ;
#include <iostream.h> }
using namespace std ; Output:
namespace name m=20
{ n=22
int m=20 ;
}
int calculate()
{
Namespace for(i=n;i>1;i--)
{
f*=i;
#include <iostream>
using namespace std; }
namespace factorial return f;
{ }
void display()
int n,i,f=1; {
void input() cout<<"factorial="<<calculate();
{
}
cout<<"enter number"; }
cin>>n; int main()
{
} factorial::input();
factorial::display();
return 0;
}
********** end*************

You might also like