banner



How To Make A Clear Function While Using A Template Class

A template is a simple and yet very powerful tool in C++. The simple idea is to pass information type as a parameter so that nosotros don't demand to write the same code for dissimilar data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write 1 sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: 'template' and 'typename'. The 2d keyword can always exist replaced past keyword 'class'.
How do templates piece of work?
Templates are expanded at compiler time. This is like macros. The difference is, the compiler does blazon checking before template expansion. The idea is simple, source code contains just function/class, but compiled lawmaking may contain multiple copies of same function/grade.

templates-cpp


Function Templates We write a generic role that can exist used for different information types. Examples of part 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)? ten: y;

}

int main()

{

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

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

cout << myMax< char >( 'g' , 'eastward' ) << endl;

return 0;

}

Output:

7 7 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 < northward - ane; i++)

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

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

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

}

int main() {

int a[v] = {10, 50, 30, twoscore, 20};

int due north = sizeof (a) / sizeof (a[0]);

bubbleSort< int >(a, northward);

cout << " Sorted assortment : " ;

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

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

cout << endl;

return 0;

}

Output

            Sorted array : 10 twenty 30 40 50          

Output:

Sorted assortment : 10 20 xxx forty l

Course Templates Similar part templates, class templates are useful when a class defines something that is independent of the data blazon. Tin can be useful for classes similar LinkedList, BinaryTree, Stack, Queue, Array, etc.
Post-obit is a simple example of template Array grade.

CPP

#include <iostream>

using namespace std;

template < typename T>

course Array {

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[s];

size = due south;

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

int arr[five] = {1, ii, 3, 4, 5};

Array< int > a(arr, 5);

a.impress();

render 0;

}

Output:

          i two iii 4 5

Can there be more than one arguments to templates?
Yes, like normal parameters, we tin laissez passer more than one data types as arguments to templates. The following example demonstrates the same.

CPP

#include<iostream>

using namespace std;

template < class T, grade U>

class A  {

T 10;

U y;

public :

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

};

int main()  {

A< char , char > a;

A< int , double > b;

return 0;

}

Output

Constructor Called Constructor Called          

Output:

Constructor Called Constructor Called

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

CPP

#include<iostream>

using namespace std;

template < course T, class U = char >

class A  {

public :

T x;

U y;

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

};

int primary()  {

A< char > a;

return 0;

}

Output:

Constructor Chosen

What is the difference between office overloading and templates?
Both office 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 in that location is a static member in a template class/function?
Each case of a template contains its ain static variable. See Templates and Static variables for more details.
What is template specialization?
Template specialization allows us to accept unlike code for a particular data type. Come across Template Specialization for more details.
Can we pass nontype parameters to templates?
We can laissez passer non-type arguments to templates. Not-blazon parameters are mainly used for specifying max or min values or any other abiding value for a item instance of a template. The of import thing to annotation nigh non-type parameters is, they must be const. The compiler must know the value of not-blazon parameters at compile fourth dimension. Because the compiler needs to create functions/classes for a specified not-type value at compile time. In below program, if nosotros replace 10000 or 25 with a variable, we get a compiler error. Please see this.
Below is a C++ program.

CPP

#include <iostream>

using namespace std;

template < course T, int max>

int arrMin(T arr[], int n)

{

int m = max;

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

if (arr[i] < yard)

m = arr[i];

return thousand;

}

int main()

{

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

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

char arr2[] = {one, 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 one

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

  • passing grapheme value past creating an objects in main() function.
  • passing integer value past creating an objects in primary() part.
  • passing float value by creating an objects in main() function.

C++

#include <iostream>

#include <conio.h>

template < class Tl>

class info

{

public :

info(TI, A)

{

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

}

};

int master()

{

clrscr();

info< char >p( 'x' );

info< int >q(22);

info< bladder >r(2.25);

return 0;

}

Output:

A = x size of data in bytes: 1 A = 22 size of data in bytes: 2  A = 2.25 size of data in bytes: 4

What is template metaprogramming?
See Template Metaprogramming
You may likewise similar to take a quiz on templates.
Coffee also supports these features. Java calls it generics .
Please write comments if you discover anything wrong, or you want to share more information about the topic discussed to a higher place.


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

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

Posted by: janousekthearly.blogspot.com

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel