Write a template function in C that returns the sum and subs

Write a template function in C++ that returns the sum and substraction of two any type of numbers.

Solution

#include <iostream>
using namespace std;

template<typename T>
T sum(T a, T b)
{
    return a+b;
}
template<typename T>
T sub(T a, T b)
{
    return a-b;
}
int main()
{
    cout << sum<int>(5, 10) << endl;
    cout << sum<unsigned int>(5, 10) << endl;
    cout << sum<float>(5.0f, 10.0f) << endl;
    cout << sum<double>(5.0, 10.0) << endl;
    cout << sub<int>(10, 5) << endl;
    cout << sub<int>(5, 10) << endl;
    cout << sub<float>(15.0f, 10.0f) << endl;
    cout << sub<unsigned int>(15, 10) << endl;
    cout << sub<double>(15.0, 10.0) << endl;
    cout << sum(5, 10) << endl; //defaults to int
    cout << sum(5.0, 10.0) << endl; //defaults to double
    cout << sub(15, 10) << endl; //defaults to int
    cout << sub(15.0, 10.0) << endl; //defaults to double
    return 0;
}

Write a template function in C++ that returns the sum and substraction of two any type of numbers.Solution#include <iostream> using namespace std; templat

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site