C++新特性变参

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值