Template non-type arguments in C++
Last Updated :
29 Dec, 2020
Prerequisite: Templates in C++
Generally, a C++ template, with a single argument looks like this:
template<typename template_name>
But it has been seen that a template can have multiple arguments. The syntax for the same would be:
template<class T1, class T2, class T3, ………, class Tn>
where, n is the number of arguments.
It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
Example 1:
template <class T, int size>
class Array {
private:
// Automatic array initialization
T Arr[size]
.....
.....
};
Explanation:
In the above example, the template supplies the size of the array as an argument. This implies that the size of the array is known to the compiler at the compile time itself. The arguments must be specified whenever a template class is created.
Example 2:
// Array of 10 integers
Array<int, 10> a1
// Array of 5 double type numbers
Array<double, 5> a2
// String of size 9
Array<char, 10> a3
where size is given as an argument to the template class.
Following are the arguments that are allowed:
Below is the program to illustrate the Non-type templates:
C++
#include <iostream>
using namespace std;
template < class T>
void swap_(T* x, T* y)
{
T temp = *x;
*x = *y;
*y = temp;
}
template < class T, int size>
void bubble_sort(T arr[])
{
for ( int i = 0; i < size - 1; i++) {
for ( int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap_(&arr[j], &arr[j + 1]);
}
}
}
}
template < class T, int size>
void printArray(T arr[])
{
int i;
for (i = 0; i < size - 1; i++) {
cout << arr[i] << ", " ;
}
cout << arr[size - 1] << endl;
}
int main()
{
float arr[] = { 1.1, 1.2, 0.3, 4.55, 1.56, 0.6 };
const int size_arr = sizeof (arr) / sizeof (arr[0]);
bubble_sort< float , size_arr>(arr);
cout << "Sorted Array is: " ;
printArray< float , size_arr>(arr);
return 0;
}
|
Output:
Sorted Array is: 0.3, 0.6, 1.1, 1.2, 1.56, 4.55
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...