C3程序猿C++教程笔记——函数模板

函数模板:
对比函数重载,函数模板,只需要一个函数就搞定

具体化:就是将我们指定的类型,单独处理
template<> void fun<job>(job& j1, job& j2);
实例化:生成指定类型的函数定义
template void fun<job>(job&j1, job&j2);

#include <iostream>
using namespace std;

struct Node
{
	int a;
	double d;
};
//函数调用优先顺序,普通函数优先模板具体化函数调用,模板具体化函数优先模板函数调用
//模板函数
template<typename T>
void fun(T a )//无法使用默认参数,调用这个函数,一定要传参数
{
	cout << a << endl;
}
//模板具体化函数
template<> void fun<Node>(Node no)
{
	cout << no.a << "  " << no.d << endl;
}
//模板具体化函数
template<> void fun<int>(int a)
{
	cout << a << endl;
}
//普通函数
void fun(int a)
{
	cout << a << endl;
}
//实例化
template void fun<double>(double f);
int main()
{
	fun(12);
	fun(12.13);
	fun('a');
	fun("abc");
	//fun();
	system("pause");
	return 0;
}
发布了80 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qiukapi/article/details/104233702