Programming and Graphics

(Kiana) #1

122 Introduction to C++ Programming and Graphics


}

#endif

This function template has two arguments whose data type is left unspecified.
The symbolTrepresenting the generic data type ofxandyis arbitrary, and can
be replaced by any other symbol or variable name. However, it is a standard
practice to useT, standing for template.


ReplacingTwith an actual data type, such asint, we obtain the familiar
function definition:


void prsum (int x, int y)

This example suggests a method of constructing the template of a function:
write out the function as usual, and then replace a chosen data type in the
input, output, or both with a generic type denoted asT.


The following main program contained in the filefava.cccalls this func-
tion template to print the sum of two integers, the sum of two real numbers,
and the sum of two strings:


#include <iostream>
#include "prsum.h"
using namespace std;

int main()
{
int i=5, j=10;
prsum<int>(i,j);

float a=4.5, b=-30.4;
prsum<float>(a,b);

string s="amphi", t="theater";
prsum<string>(s,t);

return 0;
}

The executablefavais produced by issuing the command:


c++ -o fava fava.cc

Running the executable produces on the screen:


15
-25.9
amphitheater
Free download pdf