16.4可变参数模板
之前的…就是参数包
//Args是模板参数包,rest是函数参数包
//Args表示零个或多个模板类型参数
//rest表示零个或多个函数参数
template<typename T,typename ... Args>
void foo(const T& t, const Args& ... rest);
void testo01()
{
int i = 0; double d = 3.14; string s = "how now brown cow";
//实例化 foo(const int &,const string &,const int &,const double &); 三个参数
foo(i, s, 42, d);
//实例化 foo(const string &,const int &,const char[3] &);两个参数
foo(s, 42, "hi");
//实例化 foo(const double &,const string &); 一个参数
foo(d, s);
//实例化 foo(const char[3] &,没有参数); 空包
foo("hi");
}
sizeof…运算符
template<typename T,typename ... Args>
void foo(const T& t, const Args& ... rest)
{
cout << sizeof...(Args) << endl;;
cout << sizeof...(rest) << endl;
}
16.4节练习
16.51
3 3
2 2
1 1
0 0
16.52
我的猜想没错,Args 和args的数目是一样的
16.4.1 编写可变参数函数模板
//可变参数函数通常是递归的
//终止递归的函数并打印最后一个元素的函数
//此函数必须在可变参数版本的print之前声明 要不然必定报错,
template<typename T>
ostream& print(ostream& os, const T& t)
{
return os << t; //打印最后一个参数,但不会打印分隔符(,)
}
template<typename T,typename... Args>
ostream& print(ostream& os, const T& t, const Args&... rest)
{
os << t << ","; //最开始的以一个实参,而不是参数包
return print(os, rest...); //递归调用,打印其他实参
}
void test02()
{
i