Templates and it's usability in C++

Template is simple and yet very powerful features of C++. This is the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

The idea of template is to pass any data type as a parameter so that we don't need to write same code for different data types. To a large degree, a templated classes and functions are the more focused on the algorithmic thought rather than the specific nuances of a single datatype. Template makes classes or functions more reusable and easier to maintain.

So, how does it work?

Like macros, templates are expended at compiler time. The difference is, compiler does type checking before template expansion. The idea is simple, source code contains only function or class, but compiled code may contain multiple copies of same function or class.

The concept of templates can be used in two different ways:

  • Class Templates
  • Function Templates

Class Templates

A class template works in a similar to a normal class, with one key difference. Class templates are useful when a class defines something that is independent of data type. Can be useful for classes like LinkedList, BinaryTre, Stack, Queue, Array, etc.

Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions.

Here, you can find the example of a Template class.

Function Templates

Like class templates, function templates can be create for generic operations. A single function template can work with different data types at once but, a single normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use function overloading. A template parameter in function work as a special kind of parameter that can be used to pass any data type as argument, just like regular function parameters. It helps to perform the same task writing less and maintainable code.

Here, you can find the example of a Template function.