C++ 编写泛型编程

来源:互联网 发布:时间序列数据例子十年 编辑:程序博客网 时间:2024/06/15 23:27

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 >.





0 0
原创粉丝点击