六、以template进行编程

本文深入探讨了C++中的模板(template)编程,介绍了如何使用template创建函数和类,以实现泛型编程。通过二叉树类模板示例,阐述了类型参数化、成员函数定义以及模板参数在不同场景下的应用。同时,讨论了template与类型相关和独立于类型之外的部分,以及template类型参数的处理方式。
摘要由CSDN通过智能技术生成
  • Bjarne Stroustrup(C++创造者)最初将template称为被参数化的类型(parameterized type):称其参数化是因为类型相关信息可自template定义中剥离,称其类型则因为每个class template或function template基本上都随着他所作用或它所包含的类型而有性质上的变化,本身就像某种类型。
  • template(模板)能根据用户指定的特定值或特定类型,自动产生一个函数或类。
  • 二叉树(binary tree)class template包含两个class,BinaryTree用来储存指向根节点的指针,BTnode用来储存节点实值以及连接至左、右两个节点的链接。节点实值的类型(value type)正是我们希望加以参数化的部分。
  • BinaryTree类提供的操作行为有:插入(insert)、移除(remove),搜寻(find),清除(clear)、以特定遍历方式打印(print),遍历方式有:中序(inorder)、前序(preorder)、后序(postorder)。
  • template机制将类定义中 与类型相关(type-dependent)独立于类型之外 的两部分分离开来。
template <typename Type>
class BinaryTree; //前置声明 

template <typename valType>
class BTnode {
   
	//针对每一种BTnode实际类型,
	//使对应的BinaryTree实例成为其friend 
	friend class BinaryTree<valType>; 
public:
	//...
private:
	valType 	_val;
	int 		_cnt; //同一值的插入次数 
	BTnode 		*_lchild;
	BTnode 		*_rchild;
};
  • BinaryTree class仅声明一个 BTnode 指针,指向二叉树的根节点:
template <typename elemType>
class BinaryTree {
   
public:
	//...
private:
	//BTnode必须以template parameter list加以限定
	BTnode<elemType> *_root;
};
  • 在class template及其member的定义中,不必以template parameter list进一步限定class template,除此之外的场合均要限定(如上所示)。
  • 为class template定义一个inline函数,做法和为non-template class定义一个inline函数一样。但是,在类体外,class template member function的定义语法有所不同:
template <typename elemType> 
inline BinaryTree<elemType>:: //在class定义范围之外
BinaryTree
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值