banner



How To Make A Clear Function While Using A Template Datatype

A template is a elementary and still very powerful tool in C++. The simple idea is to pass information blazon as a parameter then that we don't need to write the same code for unlike data types. For case, a software company may need sort() for dissimilar data types. Rather than writing and maintaining the multiple codes, we can write ane sort() and laissez passer data type as a parameter.
C++ adds two new keywords to back up templates: 'template' and 'typename'. The second keyword tin can always be replaced by keyword 'class'.
How exercise templates piece of work?
Templates are expanded at compiler time. This is like macros. The difference is, the compiler does blazon checking earlier template expansion. The thought is simple, source code contains only office/grade, but compiled code may comprise multiple copies of aforementioned function/course.

templates-cpp


Function Templates We write a generic part 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 x, T y)

{

render (ten > y)? x: y;

}

int main()

{

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

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

cout << myMax< char >( 'thousand' , 'e' ) << endl;

render 0;

}

Output:

7 7 chiliad

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

CPP

#include <iostream>

using namespace std;

template < class T>

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

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

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

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

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

}

int main() {

int a[five] = {10, 50, xxx, 40, 20};

int n = 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 thirty forty l

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

CPP

#include <iostream>

using namespace std;

template < typename T>

class Array {

private :

T *ptr;

int size;

public :

Array(T arr[], int s);

void print();

};

template < typename T>

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

ptr = new T[south];

size = s;

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 main() {

int arr[5] = {1, ii, iii, 4, v};

Array< int > a(arr, 5);

a.impress();

return 0;

}

Output:

          i 2 3 4 5

Tin in that location be more than i arguments to templates?
Yes, similar normal parameters, we tin laissez passer more than one data types as arguments to templates. The following example demonstrates the aforementioned.

CPP

#include<iostream>

using namespace std;

template < class T, course U>

class A  {

T x;

U y;

public :

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

};

int main()  {

A< char , char > a;

A< int , double > b;

return 0;

}

Output

Constructor Chosen Constructor Called          

Output:

Constructor Called Constructor Called

Can we specify default value for template arguments?
Aye, like normal parameters, we tin can specify default arguments to templates. The post-obit case demonstrates the aforementioned.

CPP

#include<iostream>

using namespace std;

template < course T, class U = char >

grade A  {

public :

T 10;

U y;

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

};

int primary()  {

A< char > a;

render 0;

}

Output:

Constructor Chosen

What is the difference betwixt function overloading and templates?
Both office overloading and templates are examples of polymorphism feature of OOP. Function overloading is used when multiple functions practice similar operations, templates are used when multiple functions exercise identical operations.
What happens when there is a static member in a template form/office?
Each instance of a template contains its own static variable. Come across Templates and Static variables for more than details.
What is template specialization?
Template specialization allows usa to take different code for a particular information type. Encounter Template Specialization for more details.
Can nosotros pass nontype parameters to templates?
Nosotros tin laissez passer non-blazon arguments to templates. Non-blazon parameters are mainly used for specifying max or min values or any other constant value for a detail instance of a template. The important matter to note about not-type parameters is, they must be 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 non-type value at compile time. In below program, if nosotros supplant 10000 or 25 with a variable, nosotros get a compiler error. Please see this.
Below is a C++ plan.

CPP

#include <iostream>

using namespace std;

template < grade T, int max>

int arrMin(T arr[], int n)

{

int yard = max;

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

if (arr[i] < thou)

m = arr[i];

return 1000;

}

int main()

{

int arr1[]  = {10, twenty, 15, 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:

10 i

Here is an example of C++ program to prove different data types using constructor and template. We will perform few actions

  • passing character value by creating an objects in master() function.
  • passing integer value past creating an objects in main() function.
  • passing bladder value past creating an objects in main() role.

C++

#include <iostream>

#include <conio.h>

template < class Tl>

class info

{

public :

info(TI, A)

{

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

}

};

int main()

{

clrscr();

info< char >p( 'x' );

info< int >q(22);

info< float >r(2.25);

render 0;

}

Output:

A = 10 size of data in bytes: 1 A = 22 size of data in bytes: 2  A = ii.25 size of data in bytes: 4

What is template metaprogramming?
See Template Metaprogramming
Yous may besides like to take a quiz on templates.
Java besides supports these features. Java calls it generics .
Please write comments if you find anything incorrect, or you want to share more than information about the topic discussed above.


How To Make A Clear Function While Using A Template Datatype,

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

Posted by: smithknorted.blogspot.com

0 Response to "How To Make A Clear Function While Using A Template Datatype"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel