Templates in C++ with Examples

0
45

Templates are a very powerful feature in C++ because templates allow you to write generic programs. It means we can only write one program that is used for different types of data.

C++ is an object-oriented programming language (OOPs). Because C++ programming language viewing the problems in terms of objects rather than the functions/procedures for doing this. C++ also a free form programming language because it supports procedural programming, object-oriented programming, and generic programming. And that’s why using templates we can easily perform the generic programming in C++.

Object-oriented paradigm provides many concepts such as Classes and Objects, Inheritance, Abstraction, Encapsulation, Polymorphism, etc.

Why use Templates? ​
A single program accepts different types of data. That means, it also provides the concept of reusability and flexibility in C++. And most important C++ templates are used for generic programming. Generic means generalization and generalization means that based on the data type that you can write on the code which can work for any type of data.

There are two types of Templates available in C++ are as follows:

Function Templates
Class Templates

Function Templates
Function templates are very similar to a normal function but with one difference. In Function Templates, a function can use for different (more than one) data types at once whereas, in normal Function, a function can use only for one data type at once.

Function templates concept is the same as function overloading but function overloading’s count of lines of code is more than function templates. As function templates are easy to implement and provides generic programming features in C++, the count of lines of code is less than function overloading.

Syntax of Function Template:

Template

T function_name(T x, T y)

{

//Block of Statements

}

Example: 1. Create a simple program for addition by using Function Templates, so that means a single function takes different types of data:

First create a simple addition program by using normal function for different types of data.

Output :

As you see in above program we used three functions to create simple addition program for different types of data. But by using function templates it can be implemented in a single function.

Output:

Example: 2. Create a program to implement swapping between two numbers by using Function Templates, so that means a single function takes different types of data:

Output:

Read Full Article Here – https://brain-mentors.com/learn-templates-in-cplusplus/