AOP-Chap17-Templates

  • 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) : data(new T[n]()), size(n) {
   } 
	Array(const Array & rhs) : data(NULL), size(rhs.size) {
   
		(*this) = rhs;
	}
	~Array() {
   
		delete[] data;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值