C++模板、泛化、特化
发布日期:2021-06-30 12:11:04
浏览次数:3
分类:技术文章
本文共 2106 字,大约阅读时间需要 7 分钟。
一、模板
1.1类模板(class template)
templateclass xxx{};
1.2函数模板(function template)
templatevoid xxxx(T & x, T & y){......}
1.3成员模板(member template)
templateclass xxx{public: template xxx(const U& a) { ....... }};
泛化即全特化
二、特化
2.1模板偏特化(局部特化)
2.1.1个数的偏
templateclass xxx{ ......};// 上面T绑定为booltemplate class xxx { ......};
2.1.2范围的偏
// =================一==========================templateclass xxx{ ......};// =============================================// =================二==========================// 模板范围指定在指针类型的偏特化template class xxx { ......};// =============================================// 例子xxx obj1; //用的是类模板的全特化,任意类型用代码一xxx obj2; //用的是指针类型偏特化,指针类型用代码二
三、模板模板参数(template template parameter)
templateclass Container >class YYY{private: Container c; ......};// 例子template using MyList = list >;YYY mylst1; // 错误YYY mylst2; // 正确
四、可变的模板参数(variadic templates [C++11])
可变的模板参数即是:数量不定的模板参数
void print(){ ......}templatevoid print(const T& firstArg, const Types&... args){ cout << firstArg << endl; // 递归自己,args数据打印完后就没有参数了就调用最上面的没有参数的print print(args...); }
上面代码typename... Types中的...就是一个pack(包)
用于template parameters, 就是template parameters pack(模板参数包)
用于function parameter types, 就是function parameter types pack(函数参数类型包)
用于function parameters, 就是function parameters pack(函数参数包)
如果想要知道args里有多少个参数,可以用C++语言的操作符sizeof...(args)求得
实例:字符串输出
#includeusing namespace std;void show(const char* str){ cout << str;}template void show(const char* str, T t, Args... args){ while (str && *str) // 指针且字符不为空 { if (*str== '%' && *(str+1)!='%') { ++str; // 指针移动 cout << t; // 打印 show(++str, args...); // 递归继续调用 return; } else { cout << *str++; // 跳过一个字符 } }}int main(){ show("%d %f hello %% world! %s %c hello world!", 1, 1.1, "hello", 'A'); return 0;}
转载地址:https://jadeshu.blog.csdn.net/article/details/109372289 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月08日 09时18分10秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
dos简单命令
2019-04-30
mysql的安装与卸载与Navicat远程连接
2019-04-30
java实现稀疏数组及将稀疏数组存入硬盘中
2019-04-30
2021-05-18
2019-04-30
Flutter 使用插件打开相册、相机
2019-04-30
libuv实现tcp代理服务器
2019-04-30
libuv使用不当导致的内存泄漏
2019-04-30
libuv实现ping包发送和接收
2019-04-30
linux-arm编译报错m4: unrecognized option ‘--gnu‘
2019-04-30
基础架构系列篇-系统CENTOS7安装jdk8
2019-04-30
基础架构系列篇-CENTOS7安装NGINX
2019-04-30
系统运维篇-常用的LINUX指令小计
2019-04-30
基础架构系列篇-系统centos7中安装mysql8.0.23(已更新)
2019-04-30
基础架构系列篇-系统centos7中DOCKER安装REDIS(已更新)
2019-04-30
基础架构系列篇-系统centos7安装docker+COMPOSE
2019-04-30
基础架构系列篇-系统centos7中docker安装rabbitmq
2019-04-30
基础架构系列篇-NGINX部署VUE
2019-04-30
个人电商项目,基于uni-app+ springcloud +VUE技术
2019-04-30
基础架构系列篇-系统centos7安装kafka
2019-04-30
基础架构系列篇-系统centos7中docker安装分布式文件存储服务minio
2019-04-30