25 Nov 2019

  • November 25, 2019
  • Amitraj
Overloading function Templates in C++

-> We may overload a function Template either by a non - template function template.

-> if we call the name of an overloaded function template, the compiler will try to deduce its template arguments and check its explicitly declared template arguments.

-> The overloading resolution is accomplished as follows:

1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
3. Try normal overloading resolution to ordinary functions and call the one that matches.
   An error is generated if no match found.



*NOTE:  No automatic conversions are applied to arguments on the template functions.

-> Non template functions take precedence over template functions.


// Write a C++ program to demonstrate overloading of function templates.

#include<iostream>
using namespace std;
template <class T>

void f(T x,T y)
{
cout<<"Template"<<endl;
}
void f(int w,int z)
{
cout<<"Non-Template"<<endl;
}
int main()
{
f(1,2);
f('a','b');
f(1,'b');
return 0;

}

OUTPUT: 

Non-Template
Template

Non-Template


-> The function call f(1,2) could match the arguments types of both the template function and the non template function.

-> The non template function is called because a non template function takes precedence in overload resolution.

-> The function call f('a','b') can only match the argument types of the template function. The template function is called.

-> Argument deducation fails for the function call f(1,'b') , the compiler does not generate any template function specialization and overload Resolution does not take place.
   The non template function resolves this function call after using the standered conversion from char to int for the function argument 'b'.

Translate

Popular Posts