当调用一个函数时,编译器通常用函数实参来推断模板实参,用此函数实参类型代替模板实参创建出一个新的“实例”,即一个可调用的函数,这个过程叫实例化(instantiate)函数模板。该函数是得到的一个特定版本的函数。
编译器生成的函数版本,通常称为模板的实例。
int compare(const string &v1, const string &v2)
{
if(v1 < v2) return -1;
if(v2 < v1) return 1;
return 0;
}
int compare(const double &v1, const double &v2)
{
if(v1 < v2) return -1;
if(v2 < v1) return 1;
return 0;
}
// 定义compare的函数模板 // compare声明了类型为T的类型参数 // template关键字,<typename T>是模板参数列表,typename和class关键字等价,都可以使用,T是模板参数,以逗号分隔其他模板参数
template <typename T> int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; else if (v1 > v2) return 1; return 0; }
// 调用模板,将模板实参绑定到模板参数(T)上 // 调用函数模板时,编译器根据函数实参(1,0)来推断模板实参
cout << compare(1, 0) << endl; // 推断T为int
// 编译器会根据调用情况,推断出T为int,从而生成一个compare版本,T被替换为int
int compare(const T &v1, const T &v2)
{
if(v1 < v2) return -1;
if(v2 < v1) return 1;
return 0;
}
No comments:
Post a Comment