banner



How To Use Template Function In Main C++

A template is a elementary and yet very powerful tool in C++. The simple idea is to laissez passer information type as a parameter and then that we don't need to write the same code for unlike data types. For case, a software company may demand 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 ii new keywords to support templates: 'template' and 'typename'. The 2d keyword can always exist replaced by 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 earlier template expansion. The idea is unproblematic, source code contains but function/grade, but compiled code may incorporate multiple copies of aforementioned function/form.

templates-cpp


Office Templates We write a generic function that tin exist used for dissimilar 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)

{

return (x > y)? 10: y;

}

int chief()

{

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

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

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

render 0;

}

Output:

7 vii g

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 = n - 1; i < j; j--)

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

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

}

int main() {

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

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

bubbleSort< int >(a, n);

cout << " Sorted array : " ;

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

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

cout << endl;

render 0;

}

Output

            Sorted array : 10 20 30 40 50          

Output:

Sorted array : 10 20 30 forty l

Class Templates Like function templates, course templates are useful when a class defines something that is contained of the information type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
Post-obit is a simple example of template Array class.

CPP

#include <iostream>

using namespace std;

template < typename T>

form Array {

individual :

T *ptr;

int size;

public :

Assortment(T arr[], int s);

void print();

};

template < typename T>

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

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

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

Array< int > a(arr, 5);

a.print();

return 0;

}

Output:

          1 2 3 4 5

Tin there exist more than one arguments to templates?
Yeah, like normal parameters, nosotros can pass more i data types as arguments to templates. The post-obit example demonstrates the aforementioned.

CPP

#include<iostream>

using namespace std;

template < class T, form 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 Called Constructor Chosen          

Output:

Constructor Called Constructor Called

Can nosotros specify default value for template arguments?
Aye, 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 >

grade A  {

public :

T x;

U y;

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

};

int main()  {

A< char > a;

render 0;

}

Output:

Constructor Called

What is the deviation between part overloading and templates?
Both function overloading and templates are examples of polymorphism feature of OOP. Part overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations.
What happens when there is a static member in a template form/function?
Each example of a template contains its own static variable. See Templates and Static variables for more details.
What is template specialization?
Template specialization allows us to have different lawmaking for a particular data type. Meet Template Specialization for more details.
Can we pass nontype parameters to templates?
We can pass non-blazon arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other abiding value for a particular instance of a template. The of import thing to note almost not-type parameters is, they must exist 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-blazon value at compile time. In below program, if we replace 10000 or 25 with a variable, we go a compiler error. Delight come across this.
Below is a C++ plan.

CPP

#include <iostream>

using namespace std;

template < form T, int max>

int arrMin(T arr[], int n)

{

int m = max;

for ( int i = 0; i < due north; i++)

if (arr[i] < m)

m = arr[i];

render g;

}

int main()

{

int arr1[]  = {x, 20, 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 one

Hither is an example of C++ program to show dissimilar information types using constructor and template. Nosotros will perform few deportment

  • passing character value by creating an objects in main() function.
  • passing integer value by creating an objects in main() role.
  • passing float value by creating an objects in main() part.

C++

#include <iostream>

#include <conio.h>

template < form Tl>

class info

{

public :

info(TI, A)

{

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

}

};

int principal()

{

clrscr();

info< char >p( '10' );

info< int >q(22);

info< float >r(2.25);

return 0;

}

Output:

A = x size of data in bytes: ane A = 22 size of data in bytes: 2  A = ii.25 size of data in bytes: four

What is template metaprogramming?
See Template Metaprogramming
You lot may also like to accept a quiz on templates.
Java also supports these features. Coffee calls it generics .
Please write comments if y'all notice anything wrong, or you want to share more information about the topic discussed higher up.


How To Use Template Function In Main C++,

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

Posted by: rogersthoing.blogspot.com

0 Response to "How To Use Template Function In Main C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel