1.普通函数与函数模板的区别。
//普通函数可以自动发生隐式类型转换
//函数模板调用时,自动推导不会发生隐式类型转换,指定类型时会发生隐式类型转换。
//所谓隐式类型转换,即编译器根据代码,自动改变某一变量数据类型。
#include<iostream>
using namespace std ;
#include<string>
int myadd01(int a,int b){ //普通函数
return a+b;
}
template<class T> //函数模板
T myadd02(T a,T b){
return a+b;
} //发现的问题:在定义函数时,这种隐式转换的情况只能应用在 int a,而不能应用在int& a.
//这意味着,隐式类型转换作用在,定义的数据类型之间,而不能是引用或指针上。
void test01(){
int a = 10;
int b = 20;
char c = 'c';
cout<<myadd01(a,b)<<endl;
cout<<myadd02(a,b)<<endl;
cout<<myadd01(a,c)<<endl; //虽然数据类型不同,但编译器会将字符c隐式转换为整形数据99
//cout<<myadd02(a,c)<<endl; //自动推导数据类型情况下,代码错误。
cout<<myadd02<int>(a,c)<<endl; //当指定类型时,编译器则会实现隐式转换为整型
}
int main () {
test01();
system("pause");
return 0;
}
2.函数模板的调用规则。
//基本调用规则:
//1.有函数模板&普通函数同时存在时,优先调用普通函数
//2.可通过空模板参数列表强制调用函数模板
//3.函数模板也可以发生重载
//4.函数模板若能产生更好的匹配,优先函数模板。
#include<iostream>
using namespace std ;
#include<string>
template<class T>
void test01(T& a){
cout<<"函数模板调用"<<endl;
}
void test01(int& a){
cout<<"普通函数调用"<<endl;
}
template<class T>
void test01(T& a,T& b){
cout<<"函数模板重载"<<endl;
}
int main () {
int a = 10;
int b = 20;
char c ='c';
test01(a);//此时实现普通函数的调用
test01<>(a);//此时强制调用函数模板
test01(c);//此时函数模板更加适应,优先使用函数模板。
test01(a,b);//形参数目不同,函数模板重载。
system("pause");
return 0;
}
本文是根据B站内容:《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》:
https://www.bilibili.com/video/BV1et411b73Z?p=314 学习整理笔记。