Templates in C++

Templates are influential features of C++ which lets you to write generic programs. In simple terms, you can make a single function or else a class to work with dissimilar data types using templates.

Templates are often used in larger codebase for the determination of code reusability and tractability of the programs.

Function Templates

  • A function template works in a analogous to a normal function, with one
  • A single function template can work with altered data types on one occasion but, a single normal function can only work with one set of data types.
  • if you need to executeequal operations on two or else more types of data, you use function overloading to form two functions with the essential function declaration.
  • Nevertheless, a better attitude would be to use function templates since you can do the same task writing less and supportable code.
  • A function template starts with the keyword template.
T someFunction(T arg)
   ... .. ...

here, T is a template argument that receivesunlike data types (int, float), and class is a keyword.

You can similarly use keyword typename instead of class in the above example.

When, an argument of a data type is circulated to someFunction( ), compiler yields a new version of someFunction() for the set data type.



here, a function template Large() is well-defined that receives two arguments n1 and n2 of data type T. T means that argument can be of any data type.

Large() function returns the biggest among the two arguments using a simple conditional operation.

This way, using only a single function template substituted three matching normal functions and completed your code maintainable.

Class Templates

  • Resembling function templates, you can also make class templates for generic class operations.
  • Occasionally, you want a class implementation that is identical for all classes, only the data types used are dissimilar.
  • Generally, you would need to make a different class for each data type OR create different member variables and functions inside a single class.
  • This will needlessly bloat your code base and will be hard to retain, as a change is one class/function should be done on altogether classes/functions.

Yet, class templates make it easy to use again the same code for all data types.


   ... .. ...
   T var;
   T someOperation(T arg);
   ... .. ...

here, T is the template argument which is a placeholder for the data type used.

Exclusive the class body, a member variable var and a member function someOperation() are both of type T.


To create a class template object, you must to express the data type inside a <> when formation.


For example:






here, a class template Calculator is stated.

The class holds two private members of type T: num1 & num2, and a constructor to reset the members.


Leave A Comment

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