Programming and Graphics

(Kiana) #1

4.10 Function templates 121


Problem


4.9.1.What is the output of the following bizarre code?


#include <iostream>
using namespace std;

int main()
{
static int i=0;
i++;
cout << i << endl;
i = main();
return 0;
}

4.10 Function templates..........................


Assume that a function performs a certain task on numbers, and the same
function performs the same task on strings. For example, the function may
sort an array of numbers or alphabetize a list.


We can avoid duplicating the function by declaring it as a template and
putting it in a header file. This is one instance where the implementation of a
function must be included in the header file. The header file then becomes an
implementation-includedordefinition-includedheader file.


The reason for including the implementation in the header file is that the
template function materializes on demand. If we compile separately the source
code of the implementation, we will get an empty object code. Though some
compilers allow declaration-only header files for template functions, this is the
exception rather than the rule.


The following header fileprsum.hcontains the implementation of a func-
tion template that adds and prints two variables:


#ifndef PRSUMH
#define PRSUMH

#include <iostream>
using namespace std;

template <class T>
void prsum (T x, T y)
{
T z = x+y;
cout << z << endl;
Free download pdf