How to use function templates with arrays

Let’s suppose you would like to find the sum of integer elements and the sum of floating elements then in that case,  you need to create two separate functions

But, what if

If we can create only one function template to do both the jobs of different array functions

Here’s an example

#include <iostream>
using namespace std;
template<class T, class S>
T sum(T a[], S n)
{
    T s=0;
    for(int i=0;i<n;i++)
    {
        s=s+a[i];
    }
    return s;
}
int main()
{
    int x[5]={10,20,30,40,50};
    float y[3]={1.2,2.2,3.3};
    cout << "Integer elements sum" <<sum(x,5)<< endl;
    cout << "Float elements sum" <<sum(y,3)<< endl;
    return 0;
}

Output

Integer elements sum: 150
Float elements sum:  6.7

Note: the template class T is for array type while the class S is for int type because the size of an array will always be an integer

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.