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; } |
(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); }
Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.