当函数的业务逻辑相同但是函数的参数不相同时,让类型参数化,让程序员能够方便编程,就用到了泛型编程。
基本语法:
#include<iostream> using namespace std; //函数的业务逻辑一样但是函数的参数不一样 //void myswap01(int& a, int& b) //{ // int c = 0; // c = a; // a = b; // b = c; //} //void myswap02(char &a, char& b) //{ // char c = 0; // c = a; // a = b; // b = c; //} //函数模板 //template 告诉c++编译器要开始泛型编程 看到T时不要随意报错 template <typename T> void myswap(T &a,T &b) { T c; c = a; a = b; b = c; cout << "模板调用" << endl; } //函数模板的调用 //显示类型调用 //自动类型推导 void main() { { int x = 10; int y = 20; //myswap<int>(x, y);//显示类型调用 myswap(x, y);//自动类型推导 cout << "x =" << x << "y = " << y << endl; } { char a = 'a'; char b = 'b'; myswap<char>(a, b);//显示类型调用 cout << "a =" << a << "b = " << b << endl; } } //int main1() //{ // char a = 'a'; // char b = 'b'; // myswap02(a, b); // int x = 10; // int y = 20; // myswap01(x, y); // cout << "a = " << a << "b = " << b << endl; // cout << "x = " << x << "y = " << y << endl; // system("pause"); // return 0; //}
运行结果: