Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92383250
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-15 21:00:33

    来源:blog    作者:fatalerror99

现在考虑以下代码:

SquareMatrix sm1;
...
sm1.invert(); // call SquareMatrix::invert

SquareMatrix sm2;
...
sm2.invert(); // call SquareMatrix::invert

这里将有两个 invert 的拷贝被实例化。这两个函数不是相同的,因为一个作用于 5 x 5 矩阵,而另一个作用于 10 x 10 矩阵,但是除了常数 5 和 10 以外,这两个函数是相同的。这是一个发生 template-induced code bloat(模板导致的代码膨胀)的经典方法。

如果你看到两个函数除了一个版本使用了 5 而另一个使用了 10 之外,对应字符全部相等,你该怎么做呢?你的直觉让你创建一个取得一个值作为一个参数的函数版本,然后用 5 或 10 调用这个参数化的函数以代替复制代码。你的直觉为你提供了很好的方法!以下是一个初步过关的 SquareMatrix 的做法:

template // size-independent base class for
class SquareMatrixBase { // square matrices
protected:
 ...
 void invert(std::size_t matrixSize); // invert matrix of the given size
 ...
};

template< typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase {
private:
 using SquareMatrixBase::invert; // avoid hiding base version of
 // invert; see Item 33
public:
 ...
 void invert() { this->invert(n); } // make inline call to base class
}; // version of invert; see below
// for why "this->" is here

就像你能看到的,invert 的参数化版本是在一个 base class(基类)SquareMatrixBase 中的。与 SquareMatrix 一样,SquareMatrixBase 是一个 template(模板),但与 SquareMatrix 不一样的是,它参数化的仅仅是矩阵中的对象的类型,而没有矩阵的大小。因此,所有持有一个给定对象类型的矩阵将共享一个单一的 SquareMatrixBase class。从而,它们共享 invert 在那个 class 中的版本的单一拷贝。

SquareMatrixBase::invert 仅仅是一个计划用于 derived classes(派生类)以避免代码重复的方法,所以它是 protected 的而不是 public 的。调用它的额外成本应该为零,因为 derived classes(派生类)的 inverts 使用 inline functions(内联函数)调用 base class(基类)的版本。(这个 inline 是隐式的——参见《理解inline化的介入和排除》。)这些函数使用了 "this->" 标记,因为就像 Item 43 解释的,如果不这样,在 templatized base classes(模板化基类)中的函数名(诸如 SquareMatrixBase)被 derived classes(派生类)隐藏。还要注意 SquareMatrix 和 SquareMatrixBase 之间的继承关系是 private 的。这准确地反映了 base class(基类)存在的理由仅仅是简化 derived classes(派生类)的实现的事实,而不是表示 SquareMatrix 和 SquareMatrixBase 之间的一个概念上的 is-a 关系。(关于 private inheritance(私有继承)的信息,参见 《谨慎使用私有继承》。)

阅读(214) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~