#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;
}
变参模板函数
最新推荐文章于 2024-03-10 18:12:43 发布