function template



#include <iostream>    
#include <iomanip>    
using namespace std;


template<class T>T larger(T a, T b); //function prototype

intmain()
{

	cout << endl;
	cout << "Larger of 1.5 and 2.5 is " << larger(1.5, 2.5) << endl;
	cout << "Larger of 3.5 and 4.5 is " << larger(3.5,4.5) << endl;
	int value1 = 35;
	int value2 = 45;
	cout << "Larger of " << value1 << " and " << value2 << " is "
		<< larger(value1, value2)
		<< endl;
	long a = 9;
	long b = 8;
	cout << "Larger of " << a << " and " << b << " is "
		<< larger(a, b)
		<< endl;
	return 0;
}
//template for function to return the larger of two values
template<class T>T larger(T a, T b)
{
		return a > b ? a : b;
}


Note: The prototype defined by the template must be placed before any function instance is called. This rule is the same as the general function, so the template prototype is defined as:

template<class T>T larger(T a,T b);  //function prototype

This is actually the same as the first line of the template definition, just with a semicolon at the end of the statement. In the main function, the function larger() is called for the first time, as shown in the following statement:

cout << "Larger of 1.5 and 2.5 is " << larger(1.5, 2.5) << endl;

After executing this statement, the compiler will automatically create a larger() version that accepts an argument of type double, and then call that version. The next statement also needs to accept the larger version of double type:

cout << "Larger of 3.5 and 4.5 is " << larger(3.5,4.5) << endl;

The compiler will use the version produced by the previous statement.

The next statement using larger() is as follows;

int value1 = 35;

int value2 = 45;

cout << "Larger of " << value1 << " and " << value2 << " is "

<< larger(value1, value2)

<< endl;

Since this time a function with an argument of type int is being called, a new version of larger() is created that accepts an int argument.


The last call of the larger() function takes a new version with two long parameters:

long a = 9;
long b = 8;
cout << "Larger of " << a << " and " << b << " is "
<< larger(a, b)
<< endl;

This time we will get a new version with two long parameters, this program gets a total of three different versions of larger() from a piece of source code (with different object codes)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324700783&siteId=291194637