博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ Primer Plus 学习笔记 第十八章 可变参数
阅读量:4126 次
发布时间:2019-05-25

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

嗯。。。这不就是python的**kwargs么

有几个概念要懂

模板参数包

函数参数包

展开参数包

递归

 

先说模板参数包和函数参数包:

template<typename T>

void show_list(T value){};

这是常规的模板函数

那如果加上参数包

template
(模板参数包) void show_list(Args ... args)(函数参数包) {};

这样可以传递进多个元素,而且类型还可以不一样

展开参数包:

\\模板参数包    template
\\ 函数参数包 void show_list(Args ... args) { \\ 这是展开参数包 然后无限递归 = = show_list(args...) };

如何解决无限递归的问题

template
void show_list(T value, Args ... args) { show_list(args...) };

这样每次递归调用的时候都会少掉1个参数 直到无参为止

程序示例

#include 
#include
// 没有任何参数时调用该函数。void show_list3(){}template
void show_list3(T value, Args... args) { std::cout << value << ", " << std::endl; show_list3(args...); } int main() { int n = 14; double x = 2.71828; std::string mr = "Mr, String objects!"; show_list3(n, x); show_list3(x*x, '!', 7, mr); return 0; }

运行结果

程序改进:

输出后换行和使用按引用传递

程序示例

#include 
#include
void show_list3(){}// 增加最后的换行template
void show_list(const T& value) { std::cout << value << '\n'; }//按引用传递数据template
void show_list3(const T& value, const Args&... args) { std::cout << value << ", "; show_list3(args...); } int main() { int n = 14; double x = 2.71828; std::string mr = "Mr, String objects!"; show_list3(n, x); show_list3(x*x, '!', 7, mr); return 0; }

 

十八章就这样了。后面的两节就是大概说了下C++的其他东西和boost(加起来不到两张纸好像 反正没啥内容)

 

总结

完结 娃哈哈哈啊我要开始撸QT了瓦哈啊哈

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

你可能感兴趣的文章
模板方法模式
查看>>
数据结构之队列、栈
查看>>
数据结构之树
查看>>
数据结构之二叉树
查看>>
二叉树非递归遍历算法思悟
查看>>
红黑树算法思悟
查看>>
从山寨Spring中学习Spring IOC原理-自动装配注解
查看>>
实例区别BeanFactory和FactoryBean
查看>>
Spring后置处理器BeanPostProcessor的应用
查看>>
Spring框架的ImportSelector到底可以干嘛
查看>>
Mysql中下划线问题
查看>>
微信小程序中使用npm过程中提示:npm WARN saveError ENOENT: no such file or directory
查看>>
Xcode 11 报错,提示libstdc++.6 缺失,解决方案
查看>>
idea的安装以及简单使用
查看>>
Windows mysql 安装
查看>>
python循环语句与C语言的区别
查看>>
Vue项目中使用img图片和background背景图的使用方法
查看>>
vue 项目中图片选择路径位置static 或 assets区别
查看>>
vue项目打包后无法运行报错空白页面
查看>>
Vue 解决部署到服务器后或者build之后Element UI图标不显示问题(404错误)
查看>>