Programming and Graphics

(Kiana) #1

4.10 Function templates 125


const int n=5;
float income[n+1];
income[1]=73020;
income[2]=63250;
income[3]=83890;
income[4]=20340;
income[5]=80234;

float bottom = bsort<float> (n, income);

for(int i=1;i<=n;i++)
{
cout << setw(3) << right << i <<"";
cout << setw(15) << left << income[i] << endl;
}

return 0;
}

Running the executable produces on the screen the sorted list:


1 20340
2 63250
3 73020
4 80234
5 83890

Further properties of templates


Templates allow us to transmit values of constant parameters. As an
example, consider the code:


#include <iostream>
using namespace std;

//------prsum--------

template <class T, int n>
void prsum (T x, T y)
{
T z = x+y;
cout << n <<""<<z<<endl;
}

//------main--------

int main()
{
Free download pdf