【C/C++】C++11 Variadic Templates
Variadic Templates
1、function template:利用“参数个数逐一递减”的特性,实现递归函数调用
template <typename T, typename... Types>
void func(const T& firstArg, const Types&... args) {
处理 firstArg
func(args...);
}
例一、实现类似 python 3 的 print()
void print() { cout << endl; } // 边界条件,当args为0个时调用 template <typename T, typename... Types>
void print(const T& firstArg, const Types&... args) {
cout << firstArg << ' ';
print(args...);
} int main() {
print(7.5, "hello", bitset<>(), ); // print "7.5 hello 0000000101111001 42"
return ;
}
如果同时存在函数
template <typename... Types>
void print(const Types&... args) {
...
}
void print(const T& firstArg, const Types&... args) 与 void print(const Types&... args) 可以共存,可以编译通过。
但前者比较特化,后者比较泛化,共存时永远不会调用后者。
例二、模拟 C <cstdio> 的 printf(),引自 stackoverflow
void Printf(const char* s) {
while (*s) {
if (*s == '%' && *(++s) != '%')
throw runtime_error("invalid format string: missing arguments.");
cout << *s++;
}
} template <typename T, typename... Types>
void Printf(const char* s, const T& firstArg, const Types&... args) {
while (*s) {
if (*s == '%' && *(++s) != '%') {
cout << firstArg;
Printf(++s, args...);
return;
}
cout << *s++;
}
} int main() {
int* pi = new int;
Printf("[%p] %s = %f\n", pi, "This is pi", 3.1415926); // print "[0x21fcc20] This is pi = 3.14159"
return ;
}
2、class template:利用“参数个数逐一递减”导致“参数类型也逐一递减”的特性,实现递归继承或递归复合
例一、对 first 和 last(头尾元素)的特别处理(模板偏特化+递归)
// 使用tuple index和max index打印元素
template <int IDX, int MAX, typename... Args>
struct print_tuple {
static void print(ostream& os, const tuple<Args...>& args) {
os << get<IDX>(args) << (IDX + == MAX ? "" : ", ");
print_tuple<IDX + , MAX, Args...>::print(os, args);
}
}; // 递归结束的偏特化
template <int MAX, typename... Args>
struct print_tuple<MAX, MAX, Args...> {
static void print(ostream&, const tuple<Args...>&) {}
}; // output operator for tuple
template <typename... Args>
ostream& operator<<(ostream& os, const tuple<Args...>& args) {
os << '[';
// 需要知道tuple的元素index,用sizeof...(Args)获得元素个数
print_tuple<, sizeof...(Args), Args...>::print(os, args);
return os << ']';
} int main() {
cout << make_tuple(7.5, string("hello"), bitset<>(), ); // print "[7.5, hello, 0000000101111001, 42]"
return ;
}
例二、C++STL 中 tuple 的实现(类的递归继承)
template <typename... Values> class tuple;
template <> class tuple<> { }; template <typename Head, typename... Tail>
class tuple<Head, Tail...> : private tuple <Tail...> {
typedef tuple<Tail...> inherited;
public:
tuple() { }
tuple(Head v, Tail... vtail) : m_head(v), inherited(vtail...) { } // 调用base ctor
...
protected:
Head m_head;
};
例三、模拟 tuple(类的递归复合)
template <typename... Values> class tup;
template <> class tup<> { }; template <typename Head, typename... Tail>
class tup<Head, Tail...> {
typedef tup<Tail...> composited;
public:
tup() { }
tup(Head v, Tail... vtail) : m_head(v), m_tail(vtail...) { } // 递归复合
...
protected:
Head m_head;
composited m_tail;
};
只是这种实现 tuple 的方式内存消耗较大
【C/C++】C++11 Variadic Templates的更多相关文章
- C++11 : variadic templates(可变参数模板)
Introduction: Before the possibilities of the new C++ language standard, C++11, the use of templat ...
- 【正则表达式1】C++11正则表达式
https://www.cnblogs.com/pukaifei/p/5546968.html [正则表达式1]C++11正则表达式 头文件 #include <regex> rege ...
- 【读书笔记】2016.11.19 北航 《GDG 谷歌开发者大会》整理
2016.11.19 周六,我们在 北航参加了<GDG 谷歌开发者大会>,在web专场,聆听了谷歌公司的与会专家的技术分享. 中午免费的午餐,下午精美的下午茶,还有精湛的技术,都是我们队谷 ...
- 【编程篇】C++11系列之——临时对象分析
/*C++中返回一个对象时的实现及传说中的右值——临时对象*/ 如下代码: /**********************************************/ class CStuden ...
- 【机器学习实战】第11章 使用 Apriori 算法进行关联分析
第 11 章 使用 Apriori 算法进行关联分析 关联分析 关联分析是一种在大规模数据集中寻找有趣关系的任务. 这些关系可以有两种形式: 频繁项集(frequent item sets): 经常出 ...
- 【STM32H7教程】第11章 STM32H7移植SEGGER的硬件异常分析
完整教程下载地址:http://forum.armfly.com/forum.php?mod=viewthread&tid=86980 第11章 STM32H7移植SEGGER的硬 ...
- 【C/C++】C++11 Lambda
Lambda C++11 中 lambda 是一个匿名函数对象 最简形式 []{ cout << "lambda" << endl; }(); // pri ...
- 【转帖】iPhone 11 Pro Max皇帝版物料成本不足3500元 卖一赚二
iPhone 11 Pro Max皇帝版物料成本不足3500元 卖一赚二 https://www.cnbeta.com/articles/tech/894449.htm 供应链的掌控力很重要 苹果今年 ...
- 【python基础】第11回 数据类型内置方法 02
本章内容概要 列表内置方法 字典内置方法 元组内置方法 集合内置方法 可变类型与不可变类型 本章内容详细 1.列表内置方法 list 列表在调用内置方法之后不会产生新的值 1.1 统计列表中的数据值的 ...
随机推荐
- UDP广播 与 TCP客户端 --服务端
随着倒计时的响声,自觉无心工作,只想为祖国庆生. 最近有遇到过这样一个问题,将摄像头识别的行人,车辆实时显示在客户端中.有提供接口,会以Json的数据的形式将实时将识别的对象进行Post提交.所以我们 ...
- NOIP2015题解
D1T1模拟 #include<bits/stdc++.h> #define re(i,l,r) for(int i=(l);i<=(r);i++) using namespace ...
- 通过Long类型的出生日期算年龄
package com.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.u ...
- python list用法
a = ['张三','李四','赵六','王五'] #打印列表 print(a) #增 a.apppend('徐七') print(a) a.insert(1,'张六') print(a) #删 a. ...
- 0x16 Tire之最大的异或对
我们考虑所有的二元组(i,j)且i<j,那么本题的目标就是在其中找到Ai xorAj的最大值.也就是说,对于每个i(1≤i≤N),我们希望找到一个j(1<j<i),使AixorAj最 ...
- 使用QPlainText代替QText
1.现象 在项目开发中,经常使用QText来显示解析的数据,比如从网络中获取到一个数据包,解析成中文加以显示,当时间过久或者字符串比较多的时候,就会产生一定的卡顿,所以需要限制QText的行数,或者清 ...
- Java基础学习-Eclipse综述和运算符的使用
1.Eclipse的概述(磨刀不误砍柴工) -Eclipse是一个IDE(集成开发环境) -IDE(Intergrated Development Environment) ...
- C# Post 参数中的特殊符号处理
https://cloud.tencent.com/developer/article/1344673 http://blog.csdn.net/henulwj/article/details/791 ...
- 清除控制台 console
清除控制台 console.log(1) // console.clear() // CTRL + K // Ctrl + L // process.stdout.write('\033c'); // ...
- 剑指offer 09:变态跳台阶
题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法. /* f(n-1) = f(n-2) + f(n-3) + ... + f(0 ...