博客
关于我
C++11——variadic template
阅读量:281 次
发布时间:2019-03-01

本文共 2396 字,大约阅读时间需要 7 分钟。

例1:

//例1:void print()//递归出口{   	cout << "递归出口" << endl;}template
//版本1void print(const T&firstArg, const Types&...args){ cout << firstArg << endl; print(args...);}template
//版本2void print(const Types&...args){ cout << "test" << endl; print(args...);}//注意:版本1比版本2更特化,所以版本2永远不会被调用int main(){ print(7.5, "hello", bitset<16>(377), 42); system("pause"); return 0;}

在这里插入图片描述

例2:简单实现形参为initializer_list的max函数

//例2template
_ForwardIterator_my_max_element(_ForwardIterator _first, _ForwardIterator _last,_Compare cmp){ if (_first == _last)return _first; _ForwardIterator _result = _first; while (++_first != _last) { if (cmp(_result, _first)) _result = _first; } return _result;}//自定义比较函数functorclass cmp{ public: template
bool operator()(_Iterator1 _it1, _Iterator2 _it2)const { return *_it1 < *_it2; }};template
inline _ForwardIteratormy_max_element(_ForwardIterator _first, _ForwardIterator _last){ return _my_max_element(_first, _last, cmp());}template
inline _T my_max(initializer_list<_T>_l){ return *my_max_element(_l.begin(), _l.end());}int main(){ cout << my_max({ 1,2,5,3,7,9,5 }) << endl; cout << max({ 1,2,5,3,7,9,5 }) << endl;//这是标准库中的版本 system("pause"); return 0;}

例3:利用可变参数模板实现例2的效果

int maximum(int n)//只有1个参数时调用这个版本,是递归的出口{   	return n;}template
int maximum(int n, Args... args)//至少2个参数才可以调用这个版本{ return max(n, maximum(args...));}int main(){ cout << maximum(1, 2, 5, 3, 7, 9, 5) << endl; system("pause"); return 0;}

例4:使用可变参数模板简单实现tuple

在这里插入图片描述

对于上图的代码,要改一个错误的地方,见下图的黄标处。
在这里插入图片描述
这张图看明白后发现真的是经典!

#include
#include
#include
#include
#include
using namespace std;template
class my_tuple;//版本1template<>class my_tuple<> { };//版本1对应的全特化,作为递归的出口template
//比版本1更特化的版本2class my_tuple
:private my_tuple
{ public: //default constructor my_tuple() { } //constructor my_tuple(Head v, Tail... vtail) :m_head(v), my_tuple
(vtail...) { }//初始化列表中调用了基类的constructor Head head() { return m_head; } my_tuple
& tail() { return *this; }//返回的是直接基类的对象(派生类对象赋给一个基类引用)protected: Head m_head;};int main(){ my_tuple
t(41, 6.3, "nico"); cout << t.head() << endl;//41 cout << t.tail().head() << endl;//6.3 cout << t.tail().tail().head() << endl;//nico system("pause"); return 0;}

在这里插入图片描述

当然,上面这个例子是利用了继承的方式创建,其实也可以用嵌套(复合)的方式:
在这里插入图片描述

转载地址:http://zamt.baihongyu.com/

你可能感兴趣的文章
Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
查看>>
Nginx 学习(一):Nginx 下载和启动
查看>>
nginx 常用指令配置总结
查看>>
Nginx 常用配置清单
查看>>
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的 SSL 模块安装
查看>>
Nginx 的优化思路,并解析网站防盗链
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
nginx 禁止以ip形式访问服务器
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置服务器文件上传与下载
查看>>