C++ | Templates | Question 10
Output of following program.
#include <iostream> using namespace std; template <class 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]; return m; } int main() { int arr1[] = {10, 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; } |
chevron_right
filter_none
(A) Compiler error, template argument must be a data type.
(B)
10 1
(C)
10000 256
(D)
1 1
Answer: (B)
Explanation: We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of template. The important thing to note about non-type parameters is, they must be const. Compiler must know the value of non-type parameters at compile time. Because compiler needs to create functions/classes for a specified non-type value at compile time.
Following is another example of non-type parameters.
#include <iostream>
using namespace std;
template
T fun (T arr[], int size)
{
if (size > N)
cout << "Not possible";
T max = arr[0];
for (int i = 1; i < size; i++)
if (max < arr[i])
max = arr[i];
return max;
}
int main ()
{
int arr[] = {12, 3, 14};
cout << fun (arr, 3);
}
Recommended Posts:
- C++ | Templates | Question 9
- C++ | Templates | Question 2
- C++ | Templates | Question 10
- C++ | Templates | Question 3
- C++ | Templates | Question 4
- C++ | Templates | Question 5
- C++ | Templates | Question 6
- C++ | Templates | Question 8
- C++ | Templates | Question 1
- Templates and Default Arguments
- C++ | Misc C++ | Question 8
- C++ | Misc C++ | Question 7
- C++ | Inheritance | Question 14
- C++ | Misc C++ | Question 6
- C++ | References | Question 6



