Effective C++: Item 44 -- Factor parameter-independent code out of templates

Problem:

Using templates can lead to code bloat: binaries with replicated (or almost replicated) code, data, or both.
The result can be source code that looks fit and trim, yet object code that’s fat and flabby. Fat and flabby is rarely fashionable, so you need to know how to avoid such binary bombast.

Solution:

Your primary tool has the imposing name commonality and variability analysis.

Non-template code

When you’re writing a function and you realize that some part of the function’s implementation is essentially the same as another function’s implementation, do you just replicate the code?
Of course not. You factor the common code out of the two functions, put it into a third function, and have both of the other functions call the new one.
Similarly, if you’re writing a class and you realize that some parts of the class are the same as parts of another class, you don’t replicate the common parts. Instead, you move the common parts to a new class, then you use inheritance or composition (see Items 32, 38, and 39) to give the original classes access to the common features.

Template code

In non-template code, replication is explicit: you can see that there’s duplication between two functions or two classes. In template code, replication is implicit: there’s only one copy of the template source code, so you have to train yourself to sense the replication that may take place when a template is instantiated multiple times.

Example:
template<typename T, 		// template for n x n matrices of
			std::size_t n>	// objects of type T; see below for info
class SquareMatrix {
    		// on the size_t parameter
public:
	...
	void invert();			// invert the matrix in place
};

SquareMatrix<double, 5> sm1; 
...
sm1.invert();		// call SquareMatrix<double, 5>::invert
SquareMatrix<double, 10> sm2; 
.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值