banner



What Is The Purpose Of Template Typename Type In A Class Declaration

A template is a elementary and withal very powerful tool in C++. The uncomplicated idea is to pass data type as a parameter so that nosotros don't need to write the same code for different data types. For example, a software company may demand sort() for different data types. Rather than writing and maintaining the multiple codes, nosotros can write one sort() and pass information type equally a parameter.
C++ adds 2 new keywords to support templates: 'template' and 'typename'. The second keyword can always exist replaced by 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 thought is simple, source lawmaking contains simply part/class, but compiled code may contain multiple copies of same function/class.

templates-cpp


Function Templates We write a generic function that tin can be 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)

{

render (x > y)? x: y;

}

int chief()

{

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

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

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

return 0;

}

Output:

7 seven thou

Beneath is the program to implement Bubble 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 - i; i++)

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

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

bandy(a[j], a[j - ane]);

}

int main() {

int a[5] = {10, fifty, xxx, twoscore, 20};

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

bubbleSort< int >(a, north);

cout << " Sorted array : " ;

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

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

cout << endl;

render 0;

}

Output

            Sorted array : 10 twenty thirty xl 50          

Output:

Sorted array : x xx 30 40 50

Class Templates Like function templates, class templates are useful when a form defines something that is independent of the data blazon. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
Post-obit is a uncomplicated example of template Assortment class.

CPP

#include <iostream>

using namespace std;

template < typename T>

course Array {

private :

T *ptr;

int size;

public :

Assortment(T arr[], int s);

void impress();

};

template < typename T>

Array<T>::Array(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 principal() {

int arr[5] = {1, two, 3, iv, 5};

Array< int > a(arr, 5);

a.impress();

return 0;

}

Output:

          i 2 3 4 five

Can there exist more than one arguments to templates?
Yes, like normal parameters, we can pass more one data types as arguments to templates. The following case demonstrates the same.

CPP

#include<iostream>

using namespace std;

template < course T, form U>

class A  {

T ten;

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 Chosen Constructor Called

Can we specify default value for template arguments?
Yes, like normal parameters, we 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 chief()  {

A< char > a;

return 0;

}

Output:

Constructor Called

What is the difference between part overloading and templates?
Both function overloading and templates are examples of polymorphism feature of OOP. Function overloading is used when multiple functions do like operations, templates are used when multiple functions do identical operations.
What happens when there is a static member in a template form/office?
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 united states of america to have dissimilar code for a detail information blazon. Run across Template Specialization for more details.
Can nosotros pass nontype parameters to templates?
We can pass non-blazon arguments to templates. Not-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 notation about non-blazon parameters is, they must be const. The compiler must know the value of not-type parameters at compile fourth dimension. 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 see this.
Below is a C++ program.

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] < m)

m = arr[i];

return m;

}

int principal()

{

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

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

char arr2[] = {one, ii, three};

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

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

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

return 0;

}

Output:

10 ane

Here is an example of C++ plan to show different data types using constructor and template. We volition perform few deportment

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

C++

#include <iostream>

#include <conio.h>

template < class Tl>

course info

{

public :

info(TI, A)

{

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

}

};

int master()

{

clrscr();

info< char >p( 'ten' );

info< int >q(22);

info< float >r(2.25);

return 0;

}

Output:

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

What is template metaprogramming?
See Template Metaprogramming
You may also like to have a quiz on templates.
Java also supports these features. Java calls information technology generics .
Please write comments if y'all find annihilation incorrect, or you want to share more data about the topic discussed to a higher place.


What Is The Purpose Of Template Typename Type In A Class Declaration,

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

Posted by: humphreysedgerhy.blogspot.com

0 Response to "What Is The Purpose Of Template Typename Type In A Class Declaration"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel