Exercise 38: Function Template Maximum

Date completed: 14/09/2019

Write a program that uses a function template called maximum to determine the larger of two arguments. Test the program using integer, character and floating point number arguments.

Function Overloading

C++ enables several functions of the same name to be defined, as long as they have different signatures. This is called function overloading. The C++ compiler selects the proper function to call by examining the number, types and order of the arguments in the call. Function overloading is used to create several functions of the same name that perform similar tasks, but on different data types.

Example Code Template of Function Overloading



#include <iostream>
using namespace std; 
  
void print(int i) { 
	cout << " Here is int " << i << endl; 
} 
void print(double  f) { 
	cout << " Here is float " << f << endl; 
} 
void print(char const *c) { 
	cout << " Here is char* " << c << endl; 
} 
  
int main() { 
	print(10); 
	print(10.10); 
	print("ten"); 
	return 0; 
}


Function Templates

Overloaded functions are normally used to perform similar operations that involve different program logic on different data types. If the program logic and operations are identical for each data type, overloading may be performed more compactly and conveniently by using function templates. A single function template definition is written. Given the argument types provided in calls to this function, C++ automatically generates separate function template specializations to handle each type of call appropriately. Thus, defining a single function template essentially defines a whole family of overloaded functions.

Example Code Template of Function Templates



template < typename T > 					// or template< typename T >

T minimum( T value1, T value2, T value3 ){

	T minimumValue = value1; 				// assume value1 is minimum
	
	// determine whether value2 is less than minimumValue
	if ( value2 < minimumValue )
		minimumValue = value2;

	// determine whether value3 is less than minimumValue
	if ( value3 < minimumValue )
		minimumValue = value3;

	return minimumValue;
} // end function template minimum


The Created Code

The created source code can be found here. It has been compressed in to a 7-Zip file.

Some screen prints

Description Screen Print Out
The output as seen in Eclipse. cpp_s05_ex38 image