banner



How Does Template Function Work

A template is a simple and still very powerful tool in C++. The simple thought is to pass data blazon equally a parameter and then that we don't need to write the aforementioned code for unlike information types. For case, a software company may need sort() for different information types. Rather than writing and maintaining the multiple codes, we can write i sort() and pass data type as a parameter.
C++ adds ii new keywords to support templates: 'template' and 'typename'. The 2nd keyword can always be replaced by keyword 'form'.
How do templates work?
Templates are expanded at compiler fourth dimension. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, source lawmaking contains simply function/class, but compiled lawmaking may comprise multiple copies of same office/class.

templates-cpp


Function Templates Nosotros write a generic part that can exist used for different information 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 x, T y)

{

return (x > y)? x: y;

}

int main()

{

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

cout << myMax< double >(three.0, 7.0) << endl;

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

return 0;

}

Output:

7 seven thou

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

CPP

#include <iostream>

using namespace std;

template < course T>

void bubbleSort(T a[], int due north) {

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

for ( int j = northward - 1; i < j; j--)

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

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

}

int main() {

int a[5] = {x, fifty, 30, 40, 20};

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

bubbleSort< int >(a, n);

cout << " Sorted array : " ;

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

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

cout << endl;

return 0;

}

Output:

Sorted array : 10 20 30 40 50

Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes similar LinkedList, BinaryTree, Stack, Queue, Array, etc.
Following is a elementary example of template Assortment form.

CPP

#include <iostream>

using namespace std;

template < typename T>

class Array {

private :

T *ptr;

int size;

public :

Array(T arr[], int due south);

void print();

};

template < typename T>

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

ptr = new T[s];

size = s;

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

ptr[i] = arr[i];

}

template < typename T>

void Array<T>::print() {

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

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

cout<<endl;

}

int main() {

int arr[5] = {i, 2, 3, 4, 5};

Array< int > a(arr, 5);

a.print();

return 0;

}

Output:

          1 2 three 4 5

Can at that place be more than than one arguments to templates?
Aye, like normal parameters, we can pass more than one information types as 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;

render 0;

}

Output:

Constructor Chosen Constructor Called

Can we specify default value for template arguments?
Yes, like normal parameters, nosotros can specify default arguments to templates. The post-obit example demonstrates the same.

CPP

#include<iostream>

using namespace std;

template < class T, class U = char >

grade A  {

public :

T x;

U y;

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

};

int master()  {

A< char > a;

return 0;

}

Output:

Constructor Chosen

What is the difference between function overloading and templates?
Both role 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 practise identical operations.
What happens when at that place is a static member in a template class/part?
Each example of a template contains its own static variable. Run across Templates and Static variables for more details.
What is template specialization?
Template specialization allows us to have different lawmaking for a particular data type. See Template Specialization for more than details.
Can we pass nontype parameters to templates?
We tin pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of a template. The important thing to annotation about non-type parameters is, they must be const. The compiler must know the value of non-type parameters at compile time. Considering the compiler needs to create functions/classes for a specified non-type value at compile time. In below program, if nosotros supervene upon 10000 or 25 with a variable, we go a compiler error. Please see this.
Below is a C++ program.

CPP

#include <iostream>

using namespace std;

template < form T, int max>

int arrMin(T arr[], int due north)

{

int one thousand = max;

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

if (arr[i] < k)

m = arr[i];

render m;

}

int main()

{

int arr1[]  = {ten, 20, fifteen, 12};

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

char arr2[] = {1, 2, 3};

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

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

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

return 0;

}

Output:

ten 1

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 discover anything incorrect, or you want to share more information about the topic discussed higher up.


How Does Template Function Work,

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

Posted by: kohndeabinder.blogspot.com

0 Response to "How Does Template Function Work"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel