C++ – Functions – Overload

Simple Overload

Two different functions can have the same name if their parameters are different.


// overloading functions
#include <iostream>
using namespace std;

int operate (int a, int b)
{
  return (a*b);
}

double operate (double a, double b)
{
  return (a/b);
}

int main ()
{
  int x=5,y=2;
  double n=5.0,m=2.0;
  cout << operate (x,y) << '\n';
  cout << operate (n,m) << '\n';
  return 0;
}

The result is:
10
2.5

Overload with Template

C++ has the ability to define functions with generic types, known as function templates. With templates you will be able to overload a single functions with different data types.

The statement is:


...
template <class SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}
...


// function template
#include <iostream>
using namespace std;

template <class T>
T sum (T a, T b)
{
  T result;
  result = a + b;
  return result;
}

int main () {
  int i=5, j=6, k;
  double f=2.0, g=0.5, h;
  k=sum<int>(i,j);
  h=sum<double>(f,g);
  cout << k << '\n';
  cout << h << '\n';
  return 0;
}

The result is:
11
2.5

Overload with multiple Template parameters


// function templates
#include <iostream>
using namespace std;

template <class T, class U>
bool are_equal (T a, U b)
{
  return (a==b);
}

int main ()
{
  if (are_equal(10,10.0))
    cout << "x and y are equal\n";
  else
    cout << "x and y are not equal\n";
  return 0;
}

Overload with non-type template arguments


// template arguments
#include <iostream>
using namespace std;

template <class T, int N>
T fixed_multiply (T val)
{
  return val * N;
}

int main() {
  std::cout << fixed_multiply<int,2>(10) << '\n';
  std::cout << fixed_multiply<int,3>(10) << '\n';
}

Result is:
20
30

Notice:
(10) —> (non-type)

Reference: http://www.cplusplus.com/doc/tutorial/functions2/