Professional Documents
Culture Documents
Template: is a variable that takes different data types either built in or user
defined.
Same logic is used but on different data types so instead of rewriting the same
logic for each data type we define Template قالبonly once that uses a parameter .
when you want to use the template function or the template class you will define
the data type to be used instead of this parameter where the compiler rewrites
the template according to the defined data type (Specialization).
1.Function Template
2.Class Template
3.Special Features
1.Function Template
o Declaration:
template<class T>
or you can use typename
T abs( T n )
{
2.Class Templates
o Declaration:
template<class T>
class mypair
{
int Compare(T a,T b);
};
template<class T>
{……….//Defination}
Return Type
BUT in case that the definition is inside the scope of the class(As we used to
define functions before )
template<class T>
class mypair
{
Int Compare(T a,T b)
{……….//Defination}
};
int main() {
Mypair <int> myintegerpair;
Return 0; }
Object name
3.Special Features
i.Non-Types Parameters
o Definition:
A template non-type parameter is a special type of parameter that does
not substitute for a type, but is instead replaced by a value.
Non-type parameter
For Example:
template<class T>
class mycontainer
{string name;};
//main
Int main()
{
Myconatiner<float> floatcontainer;//
10 | P a g e Techniques of programming team CMP 2024
Myconainter<int>intconaiter;
Intcointer.getserial();
Floatcontainer.getserial(); //Synatx Error(since getserial() isn’t a
member function of class my container)
Return 0;}
• Global Function
void greater(int n)
{…..}
Template<class T>
class numbers
{
friend void greater(int n); // greater() has access to all data members //of class
numbers
}
• Another class:
class A
{…}
template<class T>
class B
{friend class A;} //all member function of class A has access to data
members of class B
for example:
the integer version of template share the same static member and another
different copy of this static member is shared by the (float,double,char,etc…)
version and so on.
GOOD LUCK