int square(int number)
{
return number * number;
}
double square(double number)
{
return number * number;
}
这两个函数之间的唯一区别是它们的返回值及其形参的数据类型。在这种情况下,编写函数模板比重载函数更方便。函数模板允许程序员编写一个单独的函数定义,以处理许多不同的数据类型,而不必为每个使用的数据类型编写单独的函数。
template<class T>
T square(T number)
{
return number * number;
}
函数模板由一个模板前缀标记开始,该模板前缀以关键字 template 开始,接下来是一组尖括号,里面包含一个或多个在模板中使用的通用数据类型。通用数据类型以关键字 dass 开头,后面跟着代表数据类型的形参名称。T square(T number)
其中,T 是类型形参或通用数据类型。该函数头定义了一个 square 函数,它返回一个 T 类型的值,并使用了一个形参 number,这也是 T 类型的数字。
int y, x = 4;
y = square(x);
int square(int number)
{
return number * number;
}
但是,如果使用以下语句调用 square 函数:
double y, d = 6.2;
y = square(d);
double square(double number)
{
return number * number;
}
下面的程序演示了该函数模式的用法:
// This program uses a function template.
#include <iostream>
#include <iomanip>
using namespace std;
// Template definition for square function
template <class T>
T square(T number)
{
return number * number;
}
int main()
{
cout << setprecision(5);
//Get an integer and compute its square
cout << "Enter an integer: ";
int iValue;
cin >> iValue;
// The compiler creates int square(int) at the first occurrence of a call to square with an int argument
cout << "The square is " << square(iValue);
// Get a double and compute its square
cout << "\nEnter a double: ";
double dValue;
cin >> dValue;
// The compiler creates double square(double)at the first
// occurrence of a call to square with a double argument
cout << "The square is " << square (dValue) << endl;
return 0;
}
程序输出结果:
Enter an integer: 3
The square is 9
Enter a double: 8.3
The square is 68.89
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有