Q:

C++ program to find Sum of numbers using Overload template function

0

Write a C++ program to find Sum of numbers using Overload template function. Here’s a Simple C++ program to find Sum of numbers using Overload template function in C++ Programming Language.


What are Templates in C++ ?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

 
 

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>..


Function Template :

The general form of a template function definition is shown here:

 

template <class type> ret-type func-name(parameter list)

{
// body of function
}


Class Template :

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:

template <class type> class class-name

{
.
.
.
}


Below is the source code for C++ program to find Sum of numbers using Overload template function which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :

/* C++ program to find Sum of numbers using Overload template function  */

#include <iostream>
using namespace std;

template<class t1>
void sum(t1 a,t1 b,t1 c)
{
    cout<<"\nTemplate function 1: Sum = "<<a+b+c<<endl;
}

template <class t1,class t2>
void sum(t1 a,t1 b,t2 c)
{
    cout<<"\nTemplate function 2: Sum = "<<a+b+c<<endl;
}

void sum(int a,int b)
{
    cout<<"\nNormal function: Sum = "<<a+b<<endl;
}

int main()
{
    int a,b;
    float x,y,z;
    cout<<"\nEnter two integer data: ";
    cin>>a>>b;
    cout<<"\nEnter three float data: ";
    cin>>x>>y>>z;
    sum(x,y,z); // calls first template function
    sum(a,b,z); // calls first template function
    sum(a,b); // calls normal function
    return 0;
}

OUTPUT : :


/* C++ program to find Sum of numbers using Overload template function  */

Enter two integer data: 4
5

Enter three float data: 3.4
2.3
6.5

Template function 1: Sum = 12.2

Template function 2: Sum = 15.5

Normal function: Sum = 9

Process returned 0

Above is the source code and output for C++ program to find Sum of numbers using Overload template function which is successfully compiled and run on Windows System to produce desired output.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now