Introduction to C++ Templates

C++ FUNCTION TEMPLATE

lApproaches for functions that implement identical tasks for different data types

Naïve Approach
Function Overloading
Function Template

lInstantiating a Function Templates

NAIVE APPROCH

create unique functions with unique names for each combination of data types difficult to keeping track of multiple function names lead to programming errors

EXAMPLE

void PrintInt( int n )
{
cout << « ***Debug » << endl;
cout << « Value is  » << n << endl;
}
void PrintChar( char ch )
{
cout << « ***Debug » << endl;
cout << « Value is  » << ch << endl;
}
void PrintFloat( float x )
{

}
void PrintDouble( double d )
{

}

Approach 2:Function Overloading (Review)

The use of the same name for different C++ functions, distinguished from each other by their parameter lists. Eliminates need to come up with many different names for identical tasks. Reduces the chance of unexpected results caused by using the wrong function name.

EXAMPLE
void Print( int n )
{
cout << « ***Debug » << endl;
cout << « Value is  » << n << endl;
}
void Print( char ch )
{
cout << « ***Debug » << endl;
cout << « Value is  » << ch << endl;
}
void Print( float x )
{

}

Approach 3: Function Template
A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types.
FunctionTemplate Template < TemplateParamList >
FunctionDefinition
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *