C++拾遗--函数模板
来源:互联网 发布:詹姆斯16年总决赛数据 编辑:程序博客网 时间:2024/05/18 02:34
C++拾遗--函数模板
前言
泛型的核心思想是数据与算法分离。函数模板是泛型编程的基础。
函数模板
函数模板以 template<arg_list> 开头,arg_list是泛型参数的列表。
1.模板的泛型参数个数确定
实例一
下面是一个加法函数模板,在实例化时,我们传入普通的数据类型。
#include <iostream>using namespace std;template<typename T1, typename T2>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 <iostream>using namespace std;template<typename T, typename F>void exec(const T &t, F f){f(t);}int main(){exec("calc", system);cin.get();return 0;}运行 system("calc"); 打开计算器
2.模板的泛型参数个数不确定
#include <iostream>#include <cstdarg>using namespace std;//这个空参的函数用于递归终止void show(){}//参数个数可变,参数类型也多样template<typename T, typename...Args> //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 <iostream>#include <cstdarg>using namespace std;void PRINTF(const char *format){cout << format;}template<typename T, typename...Args>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()代码下载
本专栏目录
- C++拾遗 目录
所有内容的目录
- CCPP Blog 目录
1 0
- C++拾遗--函数模板
- C语言函数拾遗
- C/C++拾遗——main函数
- C 拾遗
- c拾遗
- 【c/c++】函数模板和模板函数
- C拾遗(三)函数式宏定义
- C/C++ 函数模板
- c++:函数模板
- 【C++】函数模板
- 【c++】函数模板
- C语言函数模板
- C++:函数模板
- 【C++】模板函数总结!!!
- C/C++:函数模板与类模板
- [C/C++]模板函数与模板类
- C++拾遗--模板元编程
- C++拾遗--函数重载
- ios 毛玻璃特效
- leetcode_110_ Balanced Binary Tree
- scala 自学笔记 高阶函数
- ThinkPHP学习心得(4)--预定义关键字
- leetcode_111_Minimum Depth of Binary Tree
- C++拾遗--函数模板
- leetcode_104_Maximum Depth of Binary Tree
- leetcode_101_Symmetric Tree
- 蓝桥杯之打印十字
- 【随笔感悟】以大多数人的努力程度之低,根本轮不到拼智商
- SVN忽略一些文件夹的更新
- Palindrome(POJ 1159)
- A. Chewbaсca and Number
- MyEclipse Derby数据库服务器使用方法