Basic of Templates in C++

Templates in C++ plays in important role in programming. It is used to make generic programs. It is also used in the STL of C++. In this post we take a look at the basics of Template and how it can be used to programming easier.

The Problem

When programming in c++ we often use function's as a way for doing repeated tasks. Say you have to add the sum of two number, then you would write a function named "sum" as below.

int sum(int a, int b) {
    return a + b;

This function would work just fine. It returns the sum of two Integer variables. Now, if you want to add the sum of two float variables or a double variables, then you should write another two function for each type of numeric values you need to perform the sum. This is where Templates come into play.

The Solution - Templates

You can define a template as shown below for the same summing function.

template<class vartype> varType sum(varType a, varType b) {
    return a + b;

The above function uses template to identify the type of the variable and the return type during run time. In the above definition both template and class are keywords. The varType is the user-defined name to identify the type. The syntax for the template declaration is:

template < class user-defined-name >

Now the function with the template can be used to compute the sum of int, float and double type. The type of sum to be performed is determined by the compiler at run-time. To use the above function we just have to call it as usual with the variables parameters of the type you expect the sum to be returned.

Sample Program

#include <iostream>
using namespace std;

// declaration.
template<class varType> varType sum(varType a, varType b);

int main() {
 // pair of integer variables.
 int a = 3, b = 5;
 // pair of float variables.
 float x = 23.4, y = 34.33;
 // pair of double variables.
 double m = 2.343434, n = 34.45454;

 cout<<"The sum of a and b interger's is : "<<sum(a, b)<<endl;
 cout<<"The sum of x and y float's is : "<<sum(x, y)<<endl;
 cout<<"The sum of m and n double's is : "<<sum(m, n)<<endl;

// definition.
template<class varType> varType sum(varType t, varType e) {
 return t + e;

The above code is a sample example of how template works. Templates could be of great use when used mindfully. Most of the STL (standard template library) Containers use template for supporting various data-types. The above code would yield the following output.

Output of the Above Source Code
Output of the above program compiled with g++

Templates can be used in declaring class methods and in creating abstract components.