- 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 {
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<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>::
BinaryTree