18 Templates
18 Templates
Templates
Function Templates
Class Templates
Templates - Genericity
Function Genericity
Function Overloading
Function Templates
Function Overloading
cout<<“Sum :”<<result;
}
Function Genericity
Templates make it possible for functions to receive not only
data values via parameters but also to receive the type of data
via a parameter.
}
Function Genericity
template <typename Item>
Item abs(Item number)
{
if (number < 0)
return –number;
else
return number;
}
Function Templates with Multiple
Arguments
template <class atype>
int find(atype array[], atype value, int size)
{
for (int j=0;j<size;j++)
if(array[j]==value)
return j;
return -1;
}
Function Templates with Multiple
Arguments
int intArr[] = {1,2,3,4,5};
int intSearch = 5;
void main()
{
cout << find(intArr,intSearch,5);
cout << find(doubleArr,dbSearch,5);
}
Template Arguments must Match
int intArray[]={1,2,3,4,5};
float f1 = 5.0;
int value = find(intArray,f1,4);
}
Review – Function Templates
• Written by programmer once
• Defines a whole family of overloaded functions
• Begins with the template keyword
• Contains a template parameter list of formal type
and the parameters for the function template are
enclosed in angle brackets (<>)
• Formal type parameters
– Preceded by keyword typename or keyword class
– Placeholders for fundamental or user-defined types
Function Template – Example
Forms
• template<typename T> f() {
}
• template<class ElementType>
g(){
}
Class Genericity
• Class-template definitions are preceded by a
header
– Such as template< typename T >
• Type parameter T can be used as a data type
in member functions and data members
• Additional type parameters can be specified
using a comma-separated list – e.g.,
– template< typename T1, typename T2 >
Class Genericity
const int CAPACITY = 128;
private:
array[CAPACITY];
};
Class Genericity
const int CAPACITY = 128;
template <typename Element>
class Test
{
public:
private:
Element array[CAPACITY];
};
Class Genericity
Without
void Test::display() Template
{
for(int i=0;i<CAPACITY;i++)
cout<<array[i];
With
}
Template
template <typename Element>
void Test<Element> :: display()
{
for(int i=0;i<CAPACITY;i++)
cout<<array[i];
}
Class Genericity
template <typename Element>
void Test<Element>::assign(Element val)
{
for(int i=0;i<CAPACITY;i++)
array[i] = val;
}
Class Genericity
void main(void)
{
Test<int> s1;
Test<float> s2;
s1.assign(5);
s2.assign(2.5);
………
………
}