Data Structures: 4. Function Templates
Data Structures: 4. Function Templates
Data Structures: 4. Function Templates
4. Function Templates
4-Function Templates 1
Function Overloading
4-Function Templates 2
Function Overloading
4-Function Templates 3
Function Overloading
• Several functions with the same name but different parameter lists
– Parameter list determines which function will execute.
4-Function Templates 4
C++ Classes
4-Function Templates 6
Generic Programming
• Advantages
– Reusability
– Writability
– Maintainability
4-Function Templates 7
Templates
4-Function Templates 8
Function Templates
• Declaration:
4-Function Templates 9
Example
int main() {
int iArray[5] = { 1, 2, 3, 4, 5 };
printArray( iArray, 5 );
// Instantiated for int[]
double y;
y = getInput(); // ??
}
4-Function Templates 11
Explicit Type Parameterization
double y;
y = getInput(); // Error!
}
4-Function Templates 12
Explicit Type Parameterization
double y;
y = getInput< double >();
}
4-Function Templates 13
User-Defined Specialization
int main( ) {
isEqual( 5, 6 ); // OK
isEqual( 7.5, 7.5 ); // OK
isEqual( “abc”, “xyz” ); // Logical Error!
return 0;
}
4-Function Templates 14
User-Defined Specialization
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
} General Template
template< >
bool isEqual< const char* >(const char* x, const char* y ) {
return ( strcmp( x, y ) == 0 );
}
User Specialization
int main( ) {
isEqual( 5, 6 ); // Target: General Template
isEqual( 7.5, 7.5 ); // Target: General Template
isEqual( “abc”, “xyz” ); // Target: User Specialization
return 0;
} 4-Function Templates 15
Multiple Type Arguments
int main() {
double d = 10.5674;
int j = my_cast( d ); //Error
int i = my_cast< int >( d );
return 0;
}
4-Function Templates 16
User-Defined Types
class String {
char* pStr;
. . .
// Operator “==“ not defined
};
4-Function Templates 17
User-Defined Types
int main() {
String s1 = “xyz”, s2 = “xyz”;
isEqual( s1, s2 ); // Error!
return 0;
}
4-Function Templates 18
User-Defined Types
class String {
char* pStr;
. . .
friend bool operator ==(const String&, const String& );
};
int main() {
String s1 = “xyz”, s2 = “xyz”;
isEqual( s1, s2 ); // OK
return 0;
}
4-Function Templates 19
Overloading vs. Templates
Function overloading
• Different data types, similar operation
• Example
– ‘+’ operation is overloaded for different operand types
Function templates
• Different data types, identical operation
• Example
– A single function template can calculate sum of array of many types
4-Function Templates 20
Overloading vs. Templates – Example
4-Function Templates 21
Overloading vs. Templates – Example
return sum;
}
4-Function Templates 22
Any Question So Far?
4-Function Templates 23