C++ 编写泛型编程

16.1.6. Writing Generic Programs

Writing Type-Independent Code

The art of writing good generic code is beyond the scope of this language primer. However, there is one overall guideline that is worth noting.


Good Practices : When writing template code, it is useful to keep the number of requirements placed on the argument types as small as possible.


Simple though it is, our comparefunction illustrates two important principles for writing generic
code:
The parameters to the template are constreferences.
The tests in the body use only <comparisons.


By making the parameters constreferences, we allow types that do not allow copying. Most typesincluding the built-in types and, except for the IO types, all the library types we've useddo allow copying. However, there can be class types that do not allow copying. By making our parameters constreferences, we ensure that such types can be used with our compare function. Moreover, if compareis called with large objects, then this design will also make the function run faster.
Some readers might think it would be more natural for the comparisons to be done using both the <and >operators:


// expected comparison
if (v1 < v2) return -1;
if (v1 > v2) return 1;
return 0;


However, by writing the code as
// expected comparison
if (v1 < v2) return -1;
if (v2 < v1) return 1; // equivalent to v1 > v2
return 0;


we reduce the requirements on types that can be used with our comparefunction. Those types
must support <, but they need not also support >.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值