-
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<typename T> //只有一个参数T,T是一个type
T * arrMax(T * array, size_t n) {
if (n == 0) {
return NULL;
}
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<typename T, typename S, int N>
int someFunction(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
int * m1 = arrMax<int>(myIntArray, nIntElements);
string * m2 = arrMax<string>(myStringArray, nStringElements);
int x = someFunction<int *, double, 42>(m1, 3.14);
- 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
template<typename T>
class Array {
private:
T * data;
size_t size;
public:
Array() : data(NULL), size(0) {
}
Array(size_t n)<