1.基本语法
#include<iostream>
using namespace std ;
#include<string>
//函数模板语法结构
template<typename T> //声明一个通用类,来写后续函数。
void myswap(T& a,T& b){ //template作为模板的关键字,声明接下来要写一个模板。
T temp = a; //typename关键字,意味着通用模板下的通用数据类型。
a = b; //可写为class,意味着通用模板下的通用类。
b = temp;
}
int main () {
int a=10;
int b=20;
double c = 1.1;
double d = 2.2;
//调用方式1:靠编译器自身推导,不用指定类型
myswap(a,b);
myswap(c,d);
//测试
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
cout<<"d="<<d<<endl;
//调用方式2:靠程序员人为指定数据类型。
myswap<int>(a,b);
myswap<double>(c,d);
//测试
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
cout<<"d="<<d<<endl;
system("pause");
return 0;
}
2.注意事项
void test01(){
int a;
double b;
//myswap(a,b);//因类型不一致此处会报错。
}
错误提示如下:
1 IntelliSense: 没有与参数列表匹配的 函数模板 “myswap” 实例
参数类型为: (int, double) d:\VS2012\code\模板\模板\函数模板.cpp
这说明在自动推导T的数据类型时,类型应保持一致。
template<class M>
void func(){
cout<<"func函数"<<endl;
}
int main () {
//func();在这种非自主推导的情形下,必须指定数据类型。
func<int>();//此时代码可以运行。
错误提示如下:
1 IntelliSense: 没有与参数列表匹配的 函数模板 “func” 实例 d:\VS2012\code\模板\模板\函数模板.cpp
这说明在这种非自主推导的情形下,必须指定数据类型。
3.函数模板综合运用案例
(数组排序)
#include<iostream>
using namespace std ;
#include<string>
template<class M>
void myswap(M& a,M& b){
M temp = a;
a=b;
b= temp;
}
template<class T>
void mysort(T arr[],int len)
{
for (int i=0;i < len;i++)
{
int max = i;
for (int j = i+1; j < len; j++)
{
if (arr[max]<arr[j])
{
max = j;
}
}
if(max!=i)
{
myswap(arr[max],arr[i]);
}
}
}
template<class N>
void arrprint(N arr[],int len){
for(int i =0;i<len;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
void test01(){
char arr[] = "abcdefg";
int num = sizeof(arr)/sizeof(char);
mysort(arr,num);
arrprint(arr,num);
}
void test02(){
int intarr[] = {1,2,3,4,5,6};
int num = sizeof(intarr)/sizeof(int);
mysort(intarr,num);
arrprint(intarr,num);
}
int main () {
test01();
test02();
system("pause");
return 0;
}
运行结果如下:
本文是根据B站内容:《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》: https://www.bilibili.com/video/BV1et411b73Z?p=314 学习整理笔记。