WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ Function Templates


Functions and classes help to make programs easier to write, safer, and more maintainable.

in certain cases they can also be somewhat limited by C++'s requirement that you specify types for all of your parameters

int sum(int x, int y) {
  return x+y;
}
Example we can now call the function for two integers in our main.
#include <iostream>
using namespace std;

int sum(int x, int y) {
    return x+y;
}

int main () {
    int x=45, y=24;
    cout << sum(x, y) << endl;
}

When we write a new function for each new type, such as doubles.
double sum(double x, double y) {
  return x+y;
}




Instead, C++ provides us with the capability of defining functions using placeholder types, called template type parameters.

To define a function template, use the keyword template:

template <class T> 

We named our template type T, which is a generic data type.

#include <iostream>
using namespace std;

template <class T>
T sum(T x, T y) {
    return x+y;
}

int main () {
    double x=71.57, y=48.3;
    cout << sum(x, y) << endl;
}


//Output
119.87



creating a template type parameter, the keyword typename may be used as an alternative to the keyword class: template <typename T>. In this context, the keywords are identical, but throughout this course, we'll use the keyword class.

Function Templates

Enhanced safety is another advantage in using template functions, since it's not necessary to manually copy functions and change types.

we can continue with our function declaration:

template <class T, class U>
T smaller(T x, U y) {
  return (x < y ? x : y);
}

template 
T smaller(T x, U y) {
    return (x < y ? x : y);
}

int main () {
    int x=58;
    double y=58.6;
    cout << smaller(x, y) << endl;
}