#include <iostream>
// 使用递归模板参数遍历所有参数,就是比较繁琐
template<typename Value>
void printf2(Value v)//递归终止函数,当剩余最后一个参数时调用
{
std::cout<<"stop"<<std::endl;
std::cout<<v<<std::endl;
}
// 递归一次,参数个数减少一个,递归调用自己
template<typename T, typename... Args>
void printf2(T t, Args... args)
{
std::cout<<t<<std::endl;
printf2(args...);
}
void test1()
{
printf2(1, 2, 3, 4, 5, "hello");
/*
printf2(1,2,3,4,5,"hello");
printf2(2,3,4,5,"hello");
printf2(3,4,5,"hello");
printf2(4,5,"hello");
printf2(5,"hello");
printf2("hello");//由终止函数调用
*/
}
// 变参模板展开,写在一个函数进行遍历,C++17
template<typename T, typename... Args>
void printf3(T t, Args... args)
{
std::cout<<t<<std::endl;
if constexpr(sizeof...(args) > 0)
{
printf3(args...);
}
}
void test2()
{
printf3(6,5,4,3,2,1,"hello");
}
// 折叠表达式
template<typename ... T>
auto sum(T ... t)
{
return (t + ...);
}
void test3()
{
std::cout << sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) << std::endl;
}
int main()
{
test1();
test2();
test3();
return 0;
}
C++新特性变参
最新推荐文章于 2025-11-11 01:15:14 发布
本文探讨了C++中递归模板函数的使用,展示了如何通过`printf2`和`printf3`函数实现参数遍历,以及折叠表达式的应用,如`sum`函数求和。通过test1、test2和test3函数的调用来展示这些技术的实际操作。
691

被折叠的 条评论
为什么被折叠?



