设为首页 加入收藏

TOP

C++拾遗--函数模板
2015-02-25 16:15:06 来源: 作者: 【 】 浏览:29
Tags:拾遗 函数 模板

前言


泛型的核心思想是数据与算法分离。函数模板是泛型编程的基础。


函数模板


函数模板以 template 开头,arg_list是泛型参数的列表。


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? ? //typename...Args是可变类型列表
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 == '\0')
? return;
?if (*format == '%')? ? //处理格式提示符
?{
? format++;
? char c = *format;
? if (c == 'd' || c == 'f' || c == 'c' || c == 'g')? //我们暂且只处理这几种,其它的同理
? {
? ?cout << t;
? ?format++;
? ?PRINTF(format, args...);
? }
? else if (c == '%')
? {
? ?cout << '%';
? ?format++;
? ?PRINTF(format, t, args...);
? }
? else
? {
? ?cout << *format;
? ?format++;
? ?PRINTF(format, t, args...);
? }
?}
?else
?{
? cout << *format;
? PRINTF(++format, t, args...);
?}
}
int main()
{
?PRINTF("%asdljl%5234la;jdfl;\n");
?PRINTF("%d alsd, %fasdf..%g..%c\n", 12, 3.4, 5.897, 'a');
?cin.get();
?return 0;
}


运行



利用函数模板简易模拟printf()代码下载


具体下载目录在 /2015年资料/2月/19日/C拾遗--函数模板/


------------------------------分割线------------------------------


C语言梳理一下,分布在以下10个章节中:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++拾遗--name_cast 显式类型转换 下一篇C++拾遗--构造函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: