变参模板函数


#include <iostream>
// 使用模板参数包定义变长模板
void Print(){}

template<typename FirstArg, typename... Args>
void Print(FirstArg first, Args... args) {
    std::cout<<first<<std::endl;
    Print(args...);// 递归调用Print模板,若参数为空时调用上面非模板函数
}
int main()
{
    Print("hello", "world", 20, true);
	/*
		Print<char const*, char const*, int, bool>("hello","world", 20,true);
		Print<char const*, int, bool>("world", 20,true);
		Print<int, bool>(20,true);
		Print<bool>(true);
		Print();
	*/
    return 0;
}

// 变参模板函数重载,若两个函数模板区别只在于尾部的参数包的时候,会优先选择没有尾部参数报的那个函数模板

template<typename T>
void Printf(T arg){
	std::cout<<arg<<std::endl;
}
template<typename FirstArg, typename... Args>
void Printf(FirstArg first, Args... args){
	Printf(first); // 会调用上面没有尾部参数包的模板函数
	Printf(args...);
}

// 一个模板函数也可以达到上面同样效果,使用到sizeof...(args)
template<typename FirstArg, typename... Args>
void PrintArgs(FirstArg first, Args... args){
	std::cout<<first<<std::endl;
	if constexpr (sizeof...(args)>0) {
		PrintArgs(args...);
	}
	else 
		std::cout<<std::endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值