banner



What Do Templates Allow Us To Accomplish In C++ That We Would Not Be Able To Do Otherwise?

A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't demand to write the same code for different information types. For example, a software company may need sort() for unlike data types. Rather than writing and maintaining the multiple codes, we can write ane sort() and pass information type every bit a parameter.
C++ adds two new keywords to back up templates: 'template' and 'typename'. The 2nd keyword tin can always be replaced past keyword 'class'.
How do templates work?
Templates are expanded at compiler time. This is like macros. The difference is, the compiler does type checking earlier template expansion. The idea is simple, source lawmaking contains only function/course, merely compiled code may contain multiple copies of same function/class.

templates-cpp


Function Templates We write a generic role that tin can be used for different data types. Examples of function templates are sort(), max(), min(), printArray().
Know more on Generics in C++

CPP

#include <iostream>

using namespace std;

template < typename T>

T myMax(T 10, T y)

{

return (x > y)? x: y;

}

int main()

{

cout << myMax< int >(3, 7) << endl;

cout << myMax< double >(3.0, 7.0) << endl;

cout << myMax< char >( 'm' , 'due east' ) << endl;

return 0;

}

Output:

vii vii g

Below is the program to implement Bubble Sort using templates in C++:

CPP

#include <iostream>

using namespace std;

template < course T>

void bubbleSort(T a[], int n) {

for ( int i = 0; i < due north - 1; i++)

for ( int j = north - i; i < j; j--)

if (a[j] < a[j - one])

swap(a[j], a[j - i]);

}

int principal() {

int a[5] = {10, l, 30, forty, 20};

int northward = sizeof (a) / sizeof (a[0]);

bubbleSort< int >(a, n);

cout << " Sorted array : " ;

for ( int i = 0; i < northward; i++)

cout << a[i] << " " ;

cout << endl;

return 0;

}

Output

            Sorted assortment : 10 20 xxx 40 l          

Output:

Sorted array : 10 20 30 xl fifty

Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Tin exist useful for classes similar LinkedList, BinaryTree, Stack, Queue, Array, etc.
Following is a simple case of template Array class.

CPP

#include <iostream>

using namespace std;

template < typename T>

grade Assortment {

private :

T *ptr;

int size;

public :

Array(T arr[], int s);

void print();

};

template < typename T>

Array<T>::Assortment(T arr[], int s) {

ptr = new T[due south];

size = due south;

for ( int i = 0; i < size; i++)

ptr[i] = arr[i];

}

template < typename T>

void Assortment<T>::print() {

for ( int i = 0; i < size; i++)

cout<< " " <<*(ptr + i);

cout<<endl;

}

int principal() {

int arr[5] = {one, two, three, 4, 5};

Array< int > a(arr, five);

a.print();

return 0;

}

Output:

          1 2 3 4 five

Can there exist more than than i arguments to templates?
Yes, similar normal parameters, we can pass more than than i data types every bit arguments to templates. The post-obit instance demonstrates the same.

CPP

#include<iostream>

using namespace std;

template < course T, class U>

class A  {

T x;

U y;

public :

A() {    cout<< "Constructor Called" <<endl;   }

};

int principal()  {

A< char , char > a;

A< int , double > b;

return 0;

}

Output

Constructor Chosen Constructor Called          

Output:

Constructor Chosen Constructor Called

Tin can we specify default value for template arguments?
Aye, similar normal parameters, nosotros can specify default arguments to templates. The following example demonstrates the aforementioned.

CPP

#include<iostream>

using namespace std;

template < class T, class U = char >

class A  {

public :

T x;

U y;

A() {   cout<< "Constructor Called" <<endl;   }

};

int main()  {

A< char > a;

return 0;

}

Output:

Constructor Called

What is the departure between function overloading and templates?
Both function overloading and templates are examples of polymorphism characteristic of OOP. Function overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations.
What happens when there is a static member in a template class/part?
Each case of a template contains its ain static variable. Encounter Templates and Static variables for more details.
What is template specialization?
Template specialization allows united states to have different code for a particular data type. See Template Specialization for more details.
Tin can we pass nontype parameters to templates?
We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or whatsoever other abiding value for a particular example of a template. The of import affair to note about not-blazon parameters is, they must exist const. The compiler must know the value of non-blazon parameters at compile time. Because the compiler needs to create functions/classes for a specified not-blazon value at compile time. In below program, if we supercede 10000 or 25 with a variable, we get a compiler error. Delight see this.
Below is a C++ program.

CPP

#include <iostream>

using namespace std;

template < class T, int max>

int arrMin(T arr[], int n)

{

int m = max;

for ( int i = 0; i < n; i++)

if (arr[i] < m)

one thousand = arr[i];

return thou;

}

int primary()

{

int arr1[]  = {10, 20, 15, 12};

int n1 = sizeof (arr1)/ sizeof (arr1[0]);

char arr2[] = {1, two, iii};

int n2 = sizeof (arr2)/ sizeof (arr2[0]);

cout << arrMin< int , 10000>(arr1, n1) << endl;

cout << arrMin< char , 256>(arr2, n2);

render 0;

}

Output:

10 ane

Here is an instance of C++ program to show dissimilar data types using constructor and template. Nosotros will perform few actions

  • passing character value past creating an objects in chief() function.
  • passing integer value by creating an objects in main() part.
  • passing float value past creating an objects in principal() function.

C++

#include <iostream>

#include <conio.h>

template < form Tl>

course info

{

public :

info(TI, A)

{

cout<< "\northward" << "A = " <<A<< " size of data in bytes:" << sizeof (ch);

}

};

int primary()

{

clrscr();

info< char >p( 'x' );

info< int >q(22);

info< float >r(2.25);

return 0;

}

Output:

A = x size of data in bytes: 1 A = 22 size of data in bytes: ii  A = two.25 size of information in bytes: 4

What is template metaprogramming?
See Template Metaprogramming
You may also like to take a quiz on templates.
Coffee also supports these features. Java calls it generics .
Please write comments if you detect anything incorrect, or y'all want to share more than information nigh the topic discussed in a higher place.


What Do Templates Allow Us To Accomplish In C++ That We Would Not Be Able To Do Otherwise?,

Source: https://www.geeksforgeeks.org/templates-cpp/

Posted by: solistheaks.blogspot.com

0 Response to "What Do Templates Allow Us To Accomplish In C++ That We Would Not Be Able To Do Otherwise?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel