本文共 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...) };
如何解决无限递归的问题
templatevoid 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/