C++拾遗–函数模板
<
div id=”content” contentScore=”2955″>前言
泛型的核心思想是数据与算法分离。函数模板是泛型编程的基础。
函数模板
函数模板以 template
1.模板的泛型参数个数确定
实例一
下面是一个加法函数模板,在实例化时,我们传入普通的数据类型。
#include
using namespace std;
template
auto add(T1 t1, T2 t2)->decltype(t1 + t2)
{
return t1 + t2;
}
int main()
{
cout << add(12.3, 12) << endl;
cout << add(12, 12.3) << endl;
cin.get();
return 0;
}
运行
实例二
我们也可以传入函数类型。
#include
using namespace std;
template
void exec(const T &t, F f)
{
f(t);
}
int main()
{
exec(“calc”, system);
cin.get();
return 0;
}
运行 system(“calc”); 打开计算器
2.模板的泛型参数个数不确定
#include
#include
using namespace std;
//这个空参的函数用于递归终止
void show()
{
}
//参数个数可变,参数类型也多样
template
void show(T t, Args…args)
{
cout << t << ends;
show(args…);
}
int main()
{
show(1, 2, 3, 4); cout << endl;
show(‘a’, ‘b’, ‘c’, ‘d’);
cin.get();
return 0;
}
运行
下面利用函数模板来简单的模仿下printf()函数
#include
#include
using namespace std;
void PRINTF(const char format)
{
cout << format;
}
template
void PRINTF(const char *format, T t, Args…args)
{
if (!format || *format == ‘