Wednesday, November 15, 2023

Overloading with Function Templates

Function templates may be overloaded. As with regular functions, function templates are overloaded by having different parameter lists.

// This program demonstrates an overloaded function template.

#include <iostream>

template <class T>

T sum(T val1, T val2)

{

return val1 + val2;

}

template <class T>

T sum(T val1, T val2, T val3)

{

return val1 + val2 + val3;

}

void main()

{

double num1, num2, num3;

// Get two values and display their sum.

cout << "Enter two values: ";

cin >> num1 >> num2;

cout << "Their sum is " << sum(num1, num2) << endl;

// Get three values and display their sum.

cout << "Enter three values: ";

cin >> num1 >> num2 >> num3;

cout << "Their sum is " << sum(num1, num2, num3) << endl;

}

 

There are two overloaded versions of the sum function in program. The first version accepts two arguments, and the second version accepts three.

There are other ways to perform overloading with function templates as well. For example, a program might contain a regular (nontemplate) version of a function as well as a template version. As long as each has a different parameter list, they can coexist as overloaded functions.

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top