0% found this document useful (0 votes)
76 views

C++ Templates: Function Template

c++ templates.

Uploaded by

Akash Sahu
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)
76 views

C++ Templates: Function Template

c++ templates.

Uploaded by

Akash Sahu
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/ 3

6/24/2017 C++Templates

C++Templates
Advertisements

PreviousPage NextPage

Templatesarethefoundationofgenericprogramming,whichinvolveswritingcodeinawaythatisindependentofanyparticulartype.

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are
examplesofgenericprogrammingandhavebeendevelopedusingtemplateconcept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector
<int>orvector<string>.

Youcanusetemplatestodefinefunctionsaswellasclasses,letusseehowdotheywork:

FunctionTemplate
Thegeneralformofatemplatefunctiondefinitionisshownhere:

template<classtype>rettypefuncname(parameterlist){
//bodyoffunction
}

Here,typeisaplaceholdernameforadatatypeusedbythefunction.Thisnamecanbeusedwithinthefunctiondefinition.

Thefollowingistheexampleofafunctiontemplatethatreturnsthemaximumoftwovalues:

#include<iostream>
#include<string>

usingnamespacestd;

template<typenameT>
inlineTconst&Max(Tconst&a,Tconst&b){
returna<b?b:a;
}

intmain(){

inti=39;
intj=20;
cout<<"Max(i,j):"<<Max(i,j)<<endl;

doublef1=13.5;
doublef2=20.7;
cout<<"Max(f1,f2):"<<Max(f1,f2)<<endl;

strings1="Hello";
strings2="World";
cout<<"Max(s1,s2):"<<Max(s1,s2)<<endl;

return0;
}

Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:

Max(i,j):39
Max(f1,f2):20.7
Max(s1,s2):World

ClassTemplate
Justaswecandefinefunctiontemplates,wecanalsodefineclasstemplates.Thegeneralformofagenericclassdeclarationisshown
here:

template<classtype>classclassname{
.
.
.
}

Here,typeistheplaceholdertypename,whichwillbespecifiedwhenaclassisinstantiated.Youcandefinemorethanonegenericdata
typebyusingacommaseparatedlist.

FollowingistheexampletodefineclassStack<>andimplementgenericmethodstopushandpoptheelementsfromthestack:

https://www.tutorialspoint.com/cplusplus/cpp_templates.htm 1/3
6/24/2017 C++Templates

#include<iostream>
#include<vector>
#include<cstdlib>
#include<string>
#include<stdexcept>

usingnamespacestd;

template<classT>
classStack
{
private:
vector<T>elements;

public:
voidpush(Tconst&);
voidpop();
Ttop();
boolempty();
};

template<classT>
voidStack<T>::push(Tconst&elem){
elements.push_back(elem);
}

template<classT>
voidStack<T>::pop(){
if(elements.empty()){
throwout_of_range("Stack<>::pop():emptystack");
}else{
elements.pop_back();
}
}

template<classT>
TStack<T>::top(){
if(empty()){
throwout_of_range("Stack<>::top():emptystack");
}
returnelements.back();
}

template<classT>
boolStack<T>::empty(){
returnelements.empty();
}

intmain(){
try{
Stack<int>intStack;//stackofints
Stack<string>stringStack;//stackofstrings

//manipulateintegerstack
intStack.push(7);
cout<<intStack.top()<<endl;

//manipulatestringstack
stringStack.push("hello");
cout<<stringStack.top()<<std::endl;
stringStack.pop();
stringStack.pop();
}
catch(exceptionconst&ex){
cerr<<"Exception:"<<ex.what()<<endl;
return1;
}
}

Ifwecompileandrunabovecode,thiswouldproducethefollowingresult:

7
hello
Exception:Stack<>::pop():emptystack

PreviousPage NextPage

Advertisements

Write for us FAQ's Helping Contact


Copyright 2017. All Rights Reserved.

https://www.tutorialspoint.com/cplusplus/cpp_templates.htm 2/3
6/24/2017 C++Templates

Enter email for newsletter go

https://www.tutorialspoint.com/cplusplus/cpp_templates.htm 3/3

You might also like