C++程序设计兼谈对象模型-04-variadic template

本文探讨了C++中的递归函数和变长参数模板(Variadic Template)技术。通过示例代码展示了如何使用变长参数模板实现可变数量和类型的参数传递,以及递归调用来处理这些参数。在`print1`函数中,参数依次打印,直至递归边界条件`print1()`终止。此外,还展示了如何利用递归来累加参数,如`foo`函数中将所有参数相加。这两个例子揭示了C++中处理变长参数的灵活性和威力。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <bitset>
using namespace std;

//1.第一步:用来终止递归
void print1() {};

//2.第二步
template <typename T, typename... Types>
void print1(const T& firstArg, const Types&... args)
{
	cout << firstArg << endl;
	print1(args...);
}

void main()
{
	print1(7.5, "hello", bitset<16>(377), 42,"I am Ty!");
	system("pause");
}

结果:
在这里插入图片描述

Variadic Template: 是指数量不定,类型不定的模板,如上所示的print函数,可以看到接受了不同类型的参数,调用的函数就是拥有Variadic Template的函数。print1(7.5, “hello”, bitset<16>(377), 42,“I am Ty!”);运行的时候,首先会7.5作为firstArg,剩余部分就是一包,然后在函数内部,继续递归调用print函数,然后把"hello"作为firstArg, 其余的作为一包,一直递归直到一包中没有数据,调用边界条件的print(空函数)结束。

void foo(int &sum)
{


}

template<typename T,typename... Args>
void foo(int &sum,const T &t, const Args&... rest)
{
	sum += t;
	foo(sum,rest...);
}


void main()
{
	int nsum = 0;
	foo(nsum,1, 100,200,300);
	cout << nsum << endl;

	system("pause");
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值