模板简介
了解函数模板以及如何在 C++ 中使用它们。
#include
int multiply ( int x, int y ) // 用于相乘两个整数 { return (x * y); }
double multiply ( double x, double y ) // 用于相乘两个双精度浮点数 { return (x * y); }
int main(){ int temp1; double temp2; temp1 = multiply(4,5); temp2 = multiply(4.5,5.5); cout << "Value of temp1 is: "<< temp1<<endl; cout << "Value of temp2 is: "<<temp2<<endl; }
template
在此情况下,关键字 class 和 typename 含义完全相同,两者可以互换使用。
以下示例展示了如何使用模板来编写 multiply 函数:
#include
template
int main() {
int result = multiply
template<class First, class Second, class Third>
#include
template<class First, class Second> void printValue ( First x, Second y ) { cout << "The first variable is:" << x <<endl; cout << "The second variable is:" << y <<endl; }
int main() { printValue<int,float> ( 2, 5.1 ); // 调用模板函数 printValue<double,char>(2.5,'a'); return 0; }