Answer to Question #193032 in C++ for Ajith M

Question #193032

Implement a C++ program to overload template function for sum of numbers.


1
Expert's answer
2021-05-20T15:13:25-0400
#include <iostream>

template<typename T>
T sum(T a, T b)
{
    return a + b;
}

template <typename T, size_t N>
T sum(const T(&data)[N])
{
    T tmp = data[0];

    for(size_t i = 1; i < N; ++i)
    {
        tmp = tmp + data[i];
    }
    
    return tmp;
}

int main()
{
    int   c1 = sum(1, 2);
    float f1 = sum(1.1f, 2.1f);
    
    int   arrC[] = {1, 2, 3, 4, 5};
    float arrF[] = {1.1f, 2.1f, 3.1f, 4.1f, 5.1f};

    int   c2 = sum(arrC);
    float f2 = sum(arrF);

    std::cout << "c1 = " << c1 << "\n";
    std::cout << "f1 = " << f1 << "\n";
    std::cout << "c2 = " << c2 << "\n";
    std::cout << "f2 = " << f2 << "\n";
    
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog