How To Instantiate A C++ Template Class In Main Method
A template is a unproblematic and yet very powerful tool in C++. The simple 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 instance, 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 2 new keywords to support templates: 'template' and 'typename'. The second keyword tin always exist replaced by keyword 'class'.
How practise templates work?
Templates are expanded at compiler fourth dimension. This is like macros. The deviation is, the compiler does type checking earlier template expansion. The idea is elementary, source code contains but role/class, but compiled code may contain multiple copies of aforementioned function/class.
Function Templates We write a generic office that can be used for different information 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)? x: y;
}
int chief()
{
cout << myMax< int >(3, 7) << endl;
cout << myMax< double >(3.0, seven.0) << endl;
cout << myMax< char >( 'yard' , 'eastward' ) << endl;
return 0;
}
Output:
7 vii g
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 northward) {
for ( int i = 0; i < n - ane; i++)
for ( int j = due north - 1; i < j; j--)
if (a[j] < a[j - ane])
bandy(a[j], a[j - 1]);
}
int chief() {
int a[5] = {ten, fifty, 30, forty, 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;
return 0;
}
Output:
Sorted assortment : ten xx 30 twoscore 50
Class Templates Like role templates, course templates are useful when a course defines something that is independent of the information type. Can exist useful for classes similar LinkedList, BinaryTree, Stack, Queue, Array, etc.
Following is a uncomplicated instance of template Array form.
CPP
#include <iostream>
using namespace std;
template < typename T>
class Assortment {
private :
T *ptr;
int size;
public :
Array(T arr[], int s);
void print();
};
template < typename T>
Assortment<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 primary() {
int arr[v] = {1, 2, iii, 4, 5};
Array< int > a(arr, 5);
a.impress();
return 0;
}
Output:
1 two three 4 v
Tin there be more than one arguments to templates?
Yeah, like normal parameters, we can pass more than ane data types as arguments to templates. The post-obit example demonstrates the aforementioned.
CPP
#include<iostream>
using namespace std;
template < class T, class U>
class A {
T x;
U y;
public :
A() { cout<< "Constructor Chosen" <<endl; }
};
int main() {
A< char , char > a;
A< int , double > b;
return 0;
}
Output:
Constructor Chosen Constructor Called
Can nosotros specify default value for template arguments?
Yes, 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, course U = char >
grade A {
public :
T x;
U y;
A() { cout<< "Constructor Called" <<endl; }
};
int main() {
A< char > a;
render 0;
}
Output:
Constructor Called
What is the divergence between function overloading and templates?
Both function overloading and templates are examples of polymorphism characteristic of OOP. Function overloading is used when multiple functions practice similar operations, templates are used when multiple functions do identical operations.
What happens when there is a static member in a template class/function?
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. to have different code for a detail information type. Come across Template Specialization for more details.
Tin can we pass nontype parameters to templates?
Nosotros can laissez passer non-type arguments to templates. Non-blazon parameters are mainly used for specifying max or min values or whatsoever other constant value for a detail instance of a template. The important thing to notation about non-type parameters is, they must be const. The compiler must know the value of not-blazon parameters at compile fourth dimension. Considering the compiler needs to create functions/classes for a specified non-type value at compile time. In below program, if we supercede 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 < class T, int max>
int arrMin(T arr[], int n)
{
int k = max;
for ( int i = 0; i < northward; i++)
if (arr[i] < one thousand)
m = arr[i];
return k;
}
int main()
{
int arr1[] = {x, 20, 15, 12};
int n1 = sizeof (arr1)/ sizeof (arr1[0]);
char arr2[] = {one, 2, 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 1
What is template metaprogramming?
Run across Template Metaprogramming
You may as well like to take a quiz on templates.
Java also supports these features. Java calls information technology generics .
Please write comments if you observe anything incorrect, or you want to share more information near the topic discussed in a higher place.
How To Instantiate A C++ Template Class In Main Method,
Source: https://www.geeksforgeeks.org/templates-cpp/
Posted by: mcculloughglelavold.blogspot.com

0 Response to "How To Instantiate A C++ Template Class In Main Method"
Post a Comment