Search⌘ K

Introduction to Templates

Explore how C++ templates allow you to write generic functions that work with multiple data types, improving code reusability and type safety. Learn to create function templates that handle various arguments, enhancing your ability to implement flexible and maintainable code.

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:

C++
#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

Templates were made to fulfill the need to design a generic code, that works the same way in different situations. Function templates offer several advantages mentioned as follows:

  • Code ...