Template Parameters and Template Arguments in C++

In this tutorial, we will learn about template parameters and template arguments in C++ along with an example.

Template in C++

Templates help us to write generic programs. Template is a keyword. By using this keyword we can define a function as a function template and a class as a class template.

Syntax of template

For funtion template:
template <parameter_list> function_declaration;

For class template:
template <parameter_list> class_declaration;

Template Parameters in C++

The parameter_list contains a list of parameters. These parameters are called template parameters.

We can specify each parameter as:
class variable_name
or
typename variable_name
These two specifications have no difference in their implementation. The parameter can also be a template. In this case, we call it a template-template parameter. We can specify the template-template parameter as:
template <template <typename> class variable_name >

Template Arguments in C++

The template arguments are those which are substituted for template parameters.

For function templates:
We can specify the arguments during the function call. The type is assigned based on the type of function arguments.
function_name(arguments);

For class templates:
We can specify the arguments at the time of object creation. The type is specified within angular brackets.
class_name <type> object();

How to use function templates in C++

A simple example showing how to use function templates.

#include <iostream>
using namespace std;

template <class t> //function template
t maximum (t a,t b)
{
  if ( a > b )
  return a;
  else
  return b;
}

int main()
{
  cout << "maximum of two int values is " << maximum (3, 4); 
  cout << endl << "maximum of two float values is " << maximum (7.2, 2.6);
  return 0;
}

Here, we created a function template with a parameter t. We specified the arguments for this parameter during the function call of maximum. Once the type is int and once the type is float.

Output:

maximum of two int values is 4
maximum of two float values is 7.2

How to use class templates

A simple example showing how to use class templates.

#include <iostream>
using namespace std;

template <class t> // class template
class demo
{
  t a;
  public: demo (t x)
      {
        a = x;
      }
      void print ()
      {
        cout << "a = " << a << endl;
      }
};

int main ()
{
  demo <int> obj1 (2);
  obj1.print();
  demo <double> obj2 (6.54);
  obj2.print();
  demo <char> obj3 ('c');
  obj3.print();
  return 0;
}

Here, we created a class template with a parameter t. We specified the type for this parameter during the object creation. Once the type is int and once the type is double and once the type is char.

Output:

a = 2
a = 6.54
a = c

Also read, Function Templates in C++

Leave a Reply

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