语法:
//函数模板的参数个数为0到多个参数,每个参数的类型可以各不相同
template<class...T>
void func1(T...args)//args一包形参,T一包类型
{
cout << sizeof...(args) << endl;//sizeof...固定语法格式计算获取到模板参数的个数
cout << sizeof...(T) << endl;;//注意sizeof...只能计算...的可变参
}
参数包展开
1.使用递归
oid func()
{
cout << "递归终止函数" << endl;
}
template<class T,class...U>
void func(T first,U... others)
{
cout << "接收到的参数" <<first<< endl;
func(others...);
}
int main()
{
func(1, 2, 3, 4,5, 6, 7, 8, 9, 10);
return 0;
}
2.使用if constexpr
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
template<class T,class...U>
void func(T first,U...others)
{
cout << "接收到的参数" << first << endl;
if constexpr(sizeof...(others)>0){
func(others...);
}
}
int main()
{
func(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
return 0;
}
if constexpr...()//constexpr代表的是常量的意思或者是编译时求值
c++17中新增的