当前位置: 首页 > 图文教程 > 开发语言 > VC++ > 用函数模板实现和优化抽象操作
| 用函数模板实现和优化抽象操作 原文出处:Optimize Abstract Operations with Function Templates
在创建完成抽象操作的函数时,如:拷贝,反转和排序,你必须定义多个版本以便能处理每一种数据类型。以 max() 函数为例,它返回两个参数中的较大者: double max(double first, double second);complex max(complex first, complex second);date max(date first, date second);//..该函数的其它版本 尽管这个函数针对不同的数据类型其实现都是一样的,但程序员必须为每一种数据类型定义一个单独的版本: double max(double first, double second){ return first>second? first : second;}complex max(complex first, complex second){ return first>second? first : second;}date max(date first, date second){ return first>second? first : second;} 这样不但重复劳动,容易出错,而且还带来很大的维护和调试工作量。更糟的是,即使你在程序中不使用某个版本,其代码仍然增加可执行文件的大小,大多数编译器将不会从可执行文件中删除未引用的函数。 // file max.h#ifndef MAX_INCLUDED#define MAX_INCLUDEDtemplate <class T> T max(T t1, T t2){ return (t1 > t2) ? t1 : t2;}#endif <class T> 定义 T 作为模板参数,或者是占位符,当实例化 max()时,它将替代具体的数据类型。max 是函数名,t1和t2是其参数,返回值的类型为 T。你可以像使用普通的函数那样使用这个 max()。编译器按照所使用的数据类型自动产生相应的模板特化,或者说是实例: int n=10,m=16;int highest = max(n,m); // 产生 int 版本std::complex<double> c1, c2;//.. 给 c1,c2 赋值std::complex<double> higher=max(c1,c2); // complex 版本 第二步:改进设计 template <class T> T max(const T& t1, const T& t2){ return (t1 > t2) ? t1 : t2;} 额外的性能问题 unsigned int htonl (unsigned int hostlong);unsigned short htons (unsigned short hostshort);unsigned int ntohl (unsigned int netlong);unsigned short ntohs (unsigned short netshort); 这些函数实现相同的操作:反转多字节值的字节。其唯一的 |