parametric polymorphism 参数多态性 --> ability of the same code to operate on different types
can write our code so that it is parameterized over what type it operates on
1 Templated Functions
keyword template followed by the template parameters in angle brackets (<>)
template parameters have a scope of the entire templated function
//找数组最大元素template<typenameT>//只有一个参数T,T是一个type
T *arrMax(T * array, size_t n){
if(n ==0){
returnNULL;}
T * ans =&array[0];for(size_t i =1; i < n; i++){
if(array[i]>*ans){
ans =&array[i];}}return ans;}
Templates may take multiple parameters, and their parameters may be “normal” types, such as int
template<typenameT,typenameS,int N>intsomeFunction(const T & t, S s){
...}
1.1 Instantiating Templated Functions
can think of a template as taking parameters and creating a function --> templated function itself is not actually a function
instantiate实例化 the template—giving it “values” for its parameters—to create an actual function
Whenever you instantiate a template, the C++ compiler creates a template specialization (or just specialization)—a “normal” function derived from a template for particular values of its parameters—if one does not already exist
2 Templated Classes
a templated class has template parameters, which can be either types or values
scope of the template parameter is the entire class declaration