banner



How To Read Template Class C++

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

templates-cpp


Part Templates Nosotros write a generic function that tin be used for different data types. Examples of role 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 >(3, 7) << endl;

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

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

return 0;

}

Output:

vii 7 g

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

CPP

#include <iostream>

using namespace std;

template < grade T>

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

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

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

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

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

}

int master() {

int a[five] = {10, l, 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 : ten 20 xxx xl 50          

Output:

Sorted array : 10 twenty xxx forty l

Class Templates Similar function templates, class templates are useful when a course defines something that is contained of the data blazon. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Assortment, etc.
Following is a elementary example 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 southward);

void print();

};

template < typename T>

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

ptr = new T[s];

size = south;

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

ptr[i] = arr[i];

}

template < typename T>

void Array<T>::impress() {

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

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

cout<<endl;

}

int chief() {

int arr[v] = {i, 2, three, 4, v};

Assortment< int > a(arr, five);

a.print();

return 0;

}

Output:

          1 ii three iv 5

Can in that location be more than than one arguments to templates?
Yes, like normal parameters, nosotros can pass more one data types equally arguments to templates. The following instance demonstrates the same.

CPP

#include<iostream>

using namespace std;

template < class T, class U>

form A  {

T ten;

U y;

public :

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

};

int main()  {

A< char , char > a;

A< int , double > b;

render 0;

}

Output

Constructor Called Constructor Called          

Output:

Constructor Called Constructor Called

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

CPP

#include<iostream>

using namespace std;

template < grade T, class U = char >

class A  {

public :

T x;

U y;

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

};

int main()  {

A< char > a;

render 0;

}

Output:

Constructor Called

What is the difference between office overloading and templates?
Both role overloading and templates are examples of polymorphism feature of OOP. Role overloading is used when multiple functions exercise 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/part?
Each instance of a template contains its own static variable. See Templates and Static variables for more details.
What is template specialization?
Template specialization allows u.s.a. to take different lawmaking for a particular information type. See Template Specialization for more details.
Can we pass nontype parameters to templates?
Nosotros can pass not-type arguments to templates. Non-blazon parameters are mainly used for specifying max or min values or whatsoever other constant value for a particular instance of a template. The important matter to notation most non-type parameters is, they must be const. The compiler must know the value of non-type 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 we replace 10000 or 25 with a variable, we get a compiler error. Please run into 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 < n; i++)

if (arr[i] < m)

m = arr[i];

render g;

}

int primary()

{

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

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

char arr2[] = {1, ii, 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 i

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

  • passing graphic symbol value by creating an objects in main() function.
  • passing integer value by creating an objects in main() function.
  • passing bladder value by creating an objects in main() function.

C++

#include <iostream>

#include <conio.h>

template < class Tl>

grade info

{

public :

info(TI, A)

{

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

}

};

int primary()

{

clrscr();

info< char >p( 'x' );

info< int >q(22);

info< float >r(two.25);

return 0;

}

Output:

A = x size of data in bytes: one A = 22 size of data in bytes: ii  A = ii.25 size of data in bytes: 4

What is template metaprogramming?
Encounter Template Metaprogramming
You lot may also similar to accept a quiz on templates.
Java besides supports these features. Java calls information technology generics .
Please write comments if you observe anything wrong, or you desire to share more information about the topic discussed in a higher place.


How To Read Template Class C++,

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

Posted by: woodbeetch.blogspot.com

0 Response to "How To Read Template Class C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel