Templates in C++

In this tutorial we will study and understand the concept of Templates in C++ and its implementation to achieve Generic programming.

Templates in C++

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. Templates are powerful features of C++ which allows you to write generic programs.
A template is a blueprint or formula for creating a generic class or a function. In simple terms, you can create a single function or a class to work with different data types using templates.
Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs. The concept of templates can be used in two different ways:

  • Function Templates
  • Class Templates

 

Templates in C++

Function Templates in C++

The general form of a template function definition is shown here:

template ret-type func-name(parameter list) {
// body of function
}

Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.

Example Program of Function Template in C++

Run Online

#include <iostream>
#include <string>

using namespace std;

template <typename T>
inline T const& Max (T const& a, T const& b)  { 
   return a < b ? b:a; 
} 

int main () {
 
   int i = 39;
   int j = 20;
   cout << "Max(i, j): " << Max(i, j) << endl; 

   double f1 = 13.5; 
   double f2 = 20.7; 
   cout << "Max(f1, f2): " << Max(f1, f2) << endl; 

   string s1 = "Hello"; 
   string s2 = "World"; 
   cout << "Max(s1, s2): " << Max(s1, s2) << endl; 

   return 0;
}
Output
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Templates in C++

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:

template <class type> class class-name {
 // code
}

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.

Example Program of Class Template in C++

Run Online

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

template <class T>
class mypair {
    T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}
    T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}
Output
Total Objects: 1
100
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *