//参考博客
//https://www.cnblogs.com/qicosmos/p/4325949.html
#include <iostream>
#include <string>
using namespace std;
//1.可变参数模板和普通模板的语义是一样的,只是写法上稍有区别。
//声明时需要在关键字class或typename后面带上省略号"..."
//典型的可变模板参数的定义:
template <class... T>
void fun(T... args)
{
cout << sizeof...(args) << endl;
}
//T... args 被称为参数包
//2.递归函数方式展开参数包
//通过递归函数展开参数包,需要提供一个参数包展开的函数和一个递归终止函数,递归终止函数正是用来终于递归的
//递归终止函数
void print()
{
cout << "empty" << endl;
}
//递归终止函数
template <class T>
void print(T t)
{
cout << t << endl;
}
//递归展开函数
template <class T, class... Args>
void print(T head, Args... rest)
{
cout << "parameeter " << head << endl;
print(rest...);
}
//3.可变参数模板,递归求和
template<typename T>
T sum(T t)
{
return t;
}
template<typename T, typename ... Types>
T sum(T first, Types ... rest)
{
return first + sum(rest...);
}
//4.逗号表达式展开参数包
//注:逗号表达式:
//(表达式1, 表达式2) 先计算表达式1,再计算表达式2,输出结果为表达式2
//(a + 3*5, a * 4) 结果为60
template <class T>
void printArg(T t)
{
cout << t << endl;
}
template <class... Args>
void expand(Args... args)
{
int arr[] = { (printArg(args), 0)... };
}
void main()
{
//例1:
{
fun();
fun(1, 2);
fun(1, 2.5, "");
}
//例2:递归展开,递归终止函数
{
print(1, 2, 3, 4);
/*
参数包Args...在展开的过程中递归调用自己,每调用一次参数包中的参数就会少一个,
直到所有的参数都展开为止,当没有参数时,则调用非模板函数printf终止递归过程。
*/
}
//例3:递归求和
{
cout<< sum(1, 2, 3, 4) << endl; //10
}
//逗号表达式&初始化列表
{
expand(1, 2, 3, 4);
}
system("pause");
return;
}
//todo