C + + support for template classes is flexible, in addition to the parameters of the template class can have type parameters, but also can have common parameters. For example:
int class demo{};
N is a common parameter that is used to pass data, rather than a type, which can be used in the body of a class like a parameter in a common function. This is called a function parameter in the template.
T is used to pass the type of data, N is used to pass the value of the data, the value and type of data can be parameterized, this is a typical object-oriented programming idea.
To demonstrate the function arguments in the template, let's define an array class:
#include <iostream>using namespacestd;template<typename T,intN>classarray{ Public: Array (); T&operator[](int ); intLength () {returnLen;}Private: intLen; T*p;}; Template<typename T,intN>Array<t, n>:: Array () {p=NewT[n]; Len=N;} Template<typename T,intN>T& Array<t, N>::operator[](inti) { if(i<0|| i>=len) cout<<"Exception:array index out of bounds!"<<Endl; returnp[i];}intMain () {Array<int,Ten>arr; intI, Len =arr.length (); for(i=0; i<len; i++) {//Assigning a value to an array elementArr[i] =2*i; } for(i=0; i<len; i++) {//iterating through an arraycout<<"arr["<<i<<"] = "<<arr[i]<<Endl; } return 0;}
In this example, a template class is defined that has a type parameter T and a common parameter, n,t, to describe the type of the array element, and N to describe the array length.
Note that the code 33rd, 36, is able to access the array element through "[]" because the operator "[]" is overloaded, and the return value is a reference to the array element. If you return the value of an array element directly, you will not be able to assign a value to the array element.
The careful reader may find that this code has the risk of memory leaks, because in the constructor, a memory is allocated through new, but not in the destructor through the delete release.
C + + Learning 35 functional parameters in templates