Logo
Section 1 / 7

模板简介

了解函数模板以及如何在 C++ 中使用它们。

导入

模板简介

了解函数模板以及如何在 C++ 中使用它们。

#include using namespace std;

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 // 或者 template

在此情况下,关键字 class 和 typename 含义完全相同,两者可以互换使用。

以下示例展示了如何使用模板来编写 multiply 函数:

#include using namespace std;

template Type multiply ( Type x, Type y ) { return (x * y); }

int main() { int result = multiply ( 2, 5 ); // 调用模板函数 cout << "Result when integer values are passed is: " << result <<endl; double result2 = multiply(2.5,5.5); cout << "Result when double values are passed is: "<<result2; return 0; }

template<class First, class Second, class Third>

#include using namespace std;

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; }

条件语句

类模板