Templates

Here we have written a Template to find the total of the elements in an array. We can't use this to find the total of strings because the + operator is not defined for strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Use template to find total of an array
#include<iostream>
#include<string>
using namespace std;
template <class T>
T findTotal(T a[],int count) {
  T total=0;
  for(int i=0;i<count;i++) {
    total+=a[i];
  }//for loop
  return total;
} //show

int main() {
   int num[]={20,5,3,17,2};
   int count=sizeof(num)/sizeof(int);
   int total=findTotal(num,count);
   cout<<"There are "<<count<<" integers, the total is "<<total<<endl;
 
   double d[]={5.5,-20, 0.25,6.1};
   count=sizeof(d)/sizeof(double);
   cout<<"There are "<<count<<" doubles, the total is "<<findTotal(d,count)<<endl;

   system("pause");
   return 0;
}//main
CODE
There are 3 integers, the total is 47
There are 4 doubles the total is -8.15
Press any key to continue . . .

NEXT: A Template bubble sort