设为首页 加入收藏

TOP

Effective C++ Item 44 将与参数无关的代码抽离 templates
2015-07-20 18:07:37 来源: 作者: 【 】 浏览:5
Tags:Effective Item 参数 无关 代码 templates
?

经验:Templates 生成多个 classes 和多个函数,所以任何 template 代码都不该与某个造成膨胀的 template 参数产生相依关系
因非类型模板参数(non-type template parameters) 而造成的代码膨胀,往往可消除,做法是以函数参数或 class 成员变量替换 template 参数


示例:
template
  
    //size_t 是非类型模板参数
class SquareMatrix{
public:
	//...
	void invert();
};
SquareMatrix
   
     sm1; sm1.invert(); SquareMatrix
    
      sm2; sm2.invert();
    
   
  


解析:具体化了两份 invert 。除了常量5和10外,其他部分完全相同
纠正:
template
  
   
class SquareMatrixBase {
protected:
	void insert(std::size_t matrixSize);
};


template
   
     //?不太懂。这里不也用了非类型模板参数吗? class SquareMatrix: private SquareMatrixBase
    
     { private: using SquareMatrixBase
     
      ::invert; //Item 33: 避免遮掩 base 版的 invert public: void invert() {this->invert(n);} // Item 34: 使用 this,derived class 才会在模板基类里找名称 }
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu1180诡异的楼梯……bfs走迷宫.. 下一篇HDU 1892 See you~

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: