Showing posts with label templates. Show all posts
Showing posts with label templates. Show all posts

Sep 11, 2020

Templates of C++ | C++ Language | Coding Winds

Templates in C++

Hello people, today we are going to read about the templates in C++. This is one of the recently added features of C++. It is a concept which enables us to define generic classes and functions and thus provide support for generic programming. Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures.

A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array.

Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are sometimes called parameterized classes or functions.

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

·       Function Templates

·       Class Templates

Function Templates

A function template operates similarly as the normally defined functions does. But with a one major key difference, that in function templates you can use parameters of different types but in normal functions we can use only the already defined type of data types.

We can also use function overloading for using a particular function with parameters different types of data types, but using functions templates is a way much better approach.

Function Templates Declaration

A function template declaration starts with a keyword template followed by templates parameters inside <……> which is followed by function declaration.


In above example, T is the argument of template which accepts different data types (int, floor) and typename is keyword.

We can also use class keyword in place of typename.

When an argument is passed to “function()” compiler generates a completely different version of the “function()” for the given data type.

Class Templates

As function templates we can also create templates for generic classes.

Sometimes, we need a class implementation that is same of all classes, only the data types used are different.

Normally, you would need to create a different class for each type or create different member variables and functions with a single class.

However, class templates make it easy to reuse the same code for all data types.

Class Templates Declaration