...

/

Introduction To Templates

Introduction To Templates

Learn about function templates and how we can use them in C++

We'll cover the following...

Definition

Templates are the mechanism by which C++ implements the generic concept.

The following example illustrates two non-generic (type-sensitive) functions for multiplying two numbers, x and y:

Press + to interact
#include <iostream>
using namespace std;
int multiply ( int x, int y ) //multiplies two ints
{
return (x * y);
}
double multiply ( double x, double y ) //multiplies two doubles
{
return (x * y);
}
int main(){
int temp1;
double temp2;
temp1 = multiply(4,5);
temp2 = multiply(4.5,5.5);
cout << "Value of temp1 is: "<< temp1<<endl;
cout << "Value of temp2 is: "<<temp2<<endl;
}

Two functions that do exactly the same thing, but cannot be defined as a single function because they use different data types.

Function Templates

...